为了账号安全,请及时绑定邮箱和手机立即绑定

如何在gin中获取参数值数组

如何在gin中获取参数值数组

Go
POPMUISE 2023-01-03 17:15:09
我需要cat_id在请求中接受多个值,例如:localhost:8080/products/?cat_id=1,2我的功能:func GenerateMultiParams(c *gin.Context) models.Params {    limit := 0    page := 1    cat_id := 1    query := c.Request.URL.Query()    for key, value := range query {        queryValue := value[len(value)-1]        switch key {        case "limit":            limit, _ = strconv.Atoi(queryValue)        case "page":            page, _ = strconv.Atoi(queryValue)        case "cat_id":            cat_id, _ = strconv.Atoi(queryValue)        }    }    return models.Params{        Limit:  limit,        Page:   page,        Cat_id: []cat_id,    }}我的结构:type Params struct {    Limit  int   `json:"limit"`    Page   int   `json:"page"`    Cat_id []int `json:"cat_id"`}在我的函数中请求:result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id=?", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod)我在网上看了很多文章,但没有一条建议对我有帮助。
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

queryValue是一个字符串,您可以对其应用您认为合适的任何操作:


func toIntArray(str string) []int {

    chunks := strings.Split(str, ",")


    var res []int

    for _, c := range chunks {

        i, _ := strconv.Atoi(c) // error handling ommitted for concision

        res = append(res, i)

    }


    return res

}

我不知道 Gin 是否有内置函数来做上面的事情


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信