3

I need to accept multiple cat_id values in the request, for example:

localhost:8080/products/?cat_id=1,2

My func:

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,
    }
}

My struct:

type Params struct {
    Limit  int   `json:"limit"`
    Page   int   `json:"page"`
    Cat_id []int `json:"cat_id"`
}

Request in my function:

result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id=?", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod)

I looked at many articles on the Internet, but not a single piece of advice helped me.

1
  • 3
    ?cat_id=1&cat_id=2 is the standard way to specify multiple values for a query parameter. Then you can do r.URL.Query()["cat_id"], this will return a []string which will contain two elements: "1" and "2". Commented Jul 24, 2022 at 12:52

1 Answer 1

3

queryValue is a string, you can apply whatever action you see fit on it :

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
}

I don't know if Gin has a built in function to do something like the above

Sign up to request clarification or add additional context in comments.

1 Comment

gin does not support it, as of this GitHub issue, which suggests the same: github.com/gin-gonic/gin/issues/1516

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.