mitchellh / mapstructure

Go library for decoding generic map values into native Go structures and vice versa.
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
7.93k stars 677 forks source link

TextUnmarshallerHookFunc panics on string based types #327

Open prochac opened 1 year ago

prochac commented 1 year ago

I don't know how it names properly, but what I mean is:

type MyString string

How I hit on the problem is with json.Decoder and UseNumber.

It marshals JSON object to map[string]any, but for JSON number it uses json.Number instead of float64, that can lose some precision.

func main() {
    hook := mapstructure.TextUnmarshallerHookFunc()

    input := json.Number("42")
    var target big.Int

    mapstructure.DecodeHookExec(
        hook,
        reflect.ValueOf(input),
        reflect.ValueOf(target),
    )
}
panic: interface conversion: interface {} is json.Number, not string
github.com/mitchellh/mapstructure.TextUnmarshallerHookFunc.func1({0x4e12c0?, 0x4aeb20?}, {0x4e12c0, 0x4b0ae0}, {0x4aeb20?, 0xc000108330})
    /tmp/gopath931946810/pkg/mod/github.com/mitchellh/mapstructure@v1.5.0/decode_hooks.go:274 +0x15c

https://go.dev/play/p/Ip7bWnkDK-r