您好我将查询参数传递给我的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"))
答案 0 :(得分:3)
从我对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'
答案 1 :(得分:0)
这可能是过度设计的,但是它为我完成了事情:
// @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