Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StringToSliceHookFunc() bug when decoding to []byte fields #323

Open
knadh opened this issue Apr 12, 2023 · 0 comments
Open

StringToSliceHookFunc() bug when decoding to []byte fields #323

knadh opened this issue Apr 12, 2023 · 0 comments

Comments

@knadh
Copy link

knadh commented Apr 12, 2023

package main

import (
	"log"

	"github.com/mitchellh/mapstructure"
)

func main() {
	o := struct {
		String []byte `json:"bytes"`
	}{}

	cfg := &mapstructure.DecoderConfig{
		DecodeHook: mapstructure.ComposeDecodeHookFunc(
			mapstructure.StringToSliceHookFunc(","),
		),
		Metadata:         nil,
		Result:           &o,
		WeaklyTypedInput: true,
		TagName:          "json",
	}

	decoder, err := mapstructure.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}

	mp := map[string]interface{}{
		"bytes": "foo",
	}
	if err := decoder.Decode(mp); err != nil {
		log.Fatal(err)
	}

}

Produces:

2023/04/12 22:03:00 1 error(s) decoding:

* cannot parse 'bytes[0]' as uint: strconv.ParseUint: parsing "foo": invalid syntax
exit status 1

This hook func should only apply when the target field is a slice of strings. However, there is no way to figure that it's a slice of strings (and only that it's a slice) from reflect.kind. Thus, unmarshalling a string to []byte fails when this hook is used. Unsure what can be done here.

t reflect.Kind,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant