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

Map as query parameter suuport Bind #2606

Open
hyzgh opened this issue Jan 8, 2021 · 6 comments
Open

Map as query parameter suuport Bind #2606

hyzgh opened this issue Jan 8, 2021 · 6 comments

Comments

@hyzgh
Copy link

hyzgh commented Jan 8, 2021

Description

I want to use a struct to bind map query parameter, it seems that gin doesn't support it yet.

How to reproduce

Run server:

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

type Req struct {
	Ext map[string]string `form:"ext"`
}

func main() {
	r := gin.Default()
	r.GET("/map", func(c *gin.Context) {
		ext := c.QueryMap("ext")
		fmt.Println(ext)
		// output: map[foo:bar]

		f := Req{}
		err := c.BindQuery(&f)
		if err != nil {
			c.Status(500)
		}
		fmt.Println(f)
		// actual output: { map[]}
		// expected output: { map[foo:bar]}
		c.Status(200)
	})

	r.Run(":8082")
}

Curl:

curl --location -g --request GET 'localhost:8082/map?ext[foo]=bar'

Environment

  • go version: Go 1.14.12
  • gin version (or commit ref): v1.6.3-0.20210112003204-f4bc259de33c
  • operating system: Darwin 19.6.0
@Doarakko
Copy link
Contributor

It seems that it will be supported in v1.7
#2484

@hyzgh
Copy link
Author

hyzgh commented Jan 12, 2021

@Doarakko Thank you for pointing that out. I update my gin dependency to the latest, but it still doesn't work. I think what that MR solves is to bind a map, as I need to bind a struct with a map embedded. It's different.

@Doarakko
Copy link
Contributor

@hyzgh
Thank you and sorry for the misunderstanding.

@dreamer2q
Copy link

mark: this feature is still not suppoted by gin.

@dreamer2q
Copy link

Somehow, the *gin.Context provides a method called QueryMap, you can use it to do your own mapping.

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

type Req struct {
	Ext map[string]string `form:"ext"`
}

func main() {
	r := gin.Default()
	r.GET("/map", func(c *gin.Context) {
		ext := c.QueryMap("ext")
		fmt.Println(ext)
		// output: map[foo:bar]

		f := Req{}
               // Take notice of this sentence
		f.Ext = c.QueryMap("Ext")
		fmt.Println(f)
		c.Status(200)
	})

	r.Run(":8082")
}

@shaicantor
Copy link

any update regarding this?

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

4 participants