Skip to content

Decoder picks only one value when array is present in query params as Array[]=x&Array[]=y #60

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

Closed
ankitaSejal opened this issue Jul 10, 2023 · 3 comments

Comments

@ankitaSejal
Copy link

ankitaSejal commented Jul 10, 2023

Package version v3.1.4

Issue: Decoder picks only one value when the array is present in query params as Array[]=x&Array[]=y

Code sample, to showcase or reproduce:

package main

import (
	"fmt"
	"log"
	"net/url"

	"github.com/go-playground/form/v4"
)

type PostsRequest struct {
	PostIds     []string
	Projections []string
}

var decoder *form.Decoder

func main() {
	decoder = form.NewDecoder()

	values := parseForm()

	var req PostsRequest

	err := decoder.Decode(&req, values)
	if err != nil {
		log.Panic(err)
	}

	fmt.Printf("%#v\n", req)
}

func parseForm() url.Values {
	return url.Values{
		"PostIds[]": []string{"1", "2"},
	}
}
@ankitaSejal
Copy link
Author

Printed response is :
main.PostsRequest{PostIds:[]string{"1"}, Projections:[]string(nil)}

@deankarn
Copy link
Contributor

@ankitaSejal There is a mismatch with the struct field name and the url.Values name which is why it appears to not be working. It's getting a single value set by total cooincidence of how the code flows(which I will be looking into further to prevent future confusion).

The struct field name is PostIds but the url .Value name is PostIds[], hence the mismatch. The PostIds[n] syntax only works when an index is specified.

Adding the form field name like so should solve your issue OR changing the url.Value to drop the brackets []

	type PostsRequest struct {
		PostIds     []string `form:"PostIds[]"`
		Projections []string
	}

@deankarn
Copy link
Contributor

I also updated the library to surface the issue to avoid confusion like this in the future https://github.com/go-playground/form/pull/61/files

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

2 participants