繁体   English   中英

从 Gin golang 读取 QueryArray

[英]Reading QueryArray from Gin golang

嗨,我正在向我的 gin 服务器传递一个查询参数,如下所示:

curl -X POST \\
'http://localhost:4000/url?X=val1&Y=val2&x[]=1&x[]=2 '

然后将其发送到我的 gin 处理程序函数

func handler (c *gin.Context) {
    fmt.Println(c.Query("X"))
    fmt.Println(c.Query("Y"))
    fmt.Println(c.QueryArray("x"))
}

虽然 c.Query("x") 和 c.Query("Y") 有效,但 c.QueryArray("x") 不起作用!

我不确定我在这里错过了什么。 我也对 GET 请求进行了相同的尝试,但它不起作用。

其他对我不起作用的实验在这里:

fmt.Println(c.Params.Get("x"))
fmt.Println(c.Params.Get("gene"))
fmt.Println(c.PostFormArray("x"))

从我对 SO 用户的评论中起草的答案。

用值重复字段名称:

curl -X POST 'http://localhost:4000/url?X=val1&Y=val2&x=1&x=2'

或:

被逗号隔开:

curl -X POST 'http://localhost:4000/url?X=val1&Y=val2&x=1,2'

这可能是过度设计的,但它为我完成了一些事情:

// @Param property_type query []uint32 false "property_types"
func (svc *HttpService) acceptListofQuery(c *gin.Context) {
    var propertyTypes []uint32
    propertyTypes, done := svc.parsePropTypes(c)
    if done {
        return
    }
    // ..... rest of logic here
    c.JSON(200, "We good")
}

func (svc *HttpService) parsePropTypes(c *gin.Context) ([]uint32, bool) {
    var propertyTypes []uint32
    var propertyTypesAsString string
    var propertyTypesAsArrayOfStrings []string
    propertyTypesAsString, success := c.GetQuery("property_types")
    propertyTypesAsArrayOfStrings = strings.Split(propertyTypesAsString, ",")
    if success {
        for _, propertyTypeAsString := range propertyTypesAsArrayOfStrings {
            i, err := strconv.Atoi(propertyTypeAsString)
            if err != nil {
                svc.ErrorWithJson(c, 400, errors.New("invalid property_types array"))
                return nil, true
            }
            propertyTypes = append(propertyTypes, uint32(i))
        }
   }
    return propertyTypes, false
}

然后你可以发送类似的东西:

curl -X POST 'http://localhost:4000/url?property_types=1,4,7,12

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM