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

Comment From: Doarakko

It seems that it will be supported in v1.7 https://github.com/gin-gonic/gin/pull/2484

Comment From: hyzgh

@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.

Comment From: Doarakko

@hyzgh Thank you and sorry for the misunderstanding.

Comment From: dreamer2q

mark: this feature is still not suppoted by gin.

Comment From: dreamer2q

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")
}

Comment From: shaicantor

any update regarding this?