【发布时间】:2021-07-09 21:52:37
【问题描述】:
我正在使用Gin Web Framework,我正在尝试找到一种方法将逗号分隔值列表从查询参数绑定到结构中。以下是我的代码的 sn-p:
type QueryParams struct {
Type []string `form:"type"`
}
func BulkRead(c *gin.Context) {
params := QueryParams{
Type: []string{},
}
if err := c.ShouldBindQuery(¶ms); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "couldn't bind query params"})
return
}
c.Status(200)
}
请求:GET /api/v1/car?type=ford,audi
我的期望:["ford", "audi"]
我得到了什么:"ford,audi"
有没有简单的方法来做到这一点?还是我需要编写一个自定义函数来处理这个问题?
【问题讨论】:
-
我想你可能需要使用
GetQueryArray。 -
我试了一下,但仍然没有给我想要的结果,
arr, _ := c.GetQueryArray("type"); fmt.Println(arr[0])->"ford,audi" -
该函数无法知道您期望多个用逗号分隔的值(为什么不是冒号或其他字符?)。也许以下请求将在任何 http 路由器中自动运行:
GET /api/v1/cart?type=ford&type=audi -
也许 rsql 是更适合您的 API 的解决方案
标签: http go query-parameters go-gin