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

我需要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)

我在网上看了很多文章,但没有一条建议对我有帮助。


POPMUISE
浏览 76回答 1
1回答

UYOU

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 是否有内置函数来做上面的事情
打开App,查看更多内容
随时随地看视频慕课网APP