Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

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 subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant