gorilla / schema

Package gorilla/schema fills a struct with form values.
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
1.37k stars 227 forks source link

[BUG] v1.2.0 Cannot decode into slice of strings #202

Closed andrewpillar closed 1 year ago

andrewpillar commented 1 year ago

Is there an existing issue for this?

Current Behavior

URL array values formatted as per the documentation are not being correctly decoded into their respective slice types for regular Go types. As of now, I have a struct,

type User struct {
    Roles []string
}

and I'm attempting to decode URL values into the struct, which are in the format of,

roles.0=admin&roles.2=moderator&roles.4=editor

as per the documentation on how slices ought to work (see the Emails.0 example toward the end).

As of now, this fails silently, I can get it to error when I do not invoke IgnoreUnknownKeys(true) on the decoder. However, the error that is reported is: schema: invalid path "roles.2" (and 2 other errors), which contradicts what the documentation previously said about working with slices.

Expected Behavior

I expect the request to be decoded without issue into the string slice. This is not the case, however, when decoding into a slice of structs, which works fine.

Steps To Reproduce

See the Go Playground here: https://go.dev/play/p/S9nkFOnxFT3?v=goprev

There is also a Role struct type in the above example, simply replace Roles []string with Roles []Role to see how decoding into a slice of structs works as expected.

Anything else?

From digging around in the source code for the library version I'm using, it appears that the root of the issue is within the cache.go file in the parsePath function.

For now, I can just use the slice of structs as a workaround. I am raising this incident in case anyone else encounters a similar issue with decoding slice values.

coreydaley commented 1 year ago

Line 22 of your Go playground link should be Roles []Role so that the code knows what type it is decoding to. https://go.dev/play/p/WJ1EKz8u3B3?v=goprev

andrewpillar commented 1 year ago

Ok, thanks for confirming the expected behaviour.