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

huangapple go评论98阅读模式
英文:

How to get an array of parameter values in gin

问题

我需要在请求中接受多个cat_id值,例如:

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

我的函数:

func GenerateMultiParams(c *gin.Context) models.Params {
	limit := 0
	page := 1
	cat_id := []int{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":
			catIDs := strings.Split(queryValue, ",")
			for _, id := range catIDs {
				idInt, _ := strconv.Atoi(id)
				cat_id = append(cat_id, idInt)
			}
		}
	}
	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 IN (?)", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod)

我查看了许多互联网上的文章,但没有一个建议对我有帮助。

英文:

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

得分: 2

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

func toIntArray(str string) []int {
    chunks := strings.Split(str, ",")

    var res []int
    for _, c := range chunks {
        i, _ := strconv.Atoi(c) // 错误处理被省略以简洁起见
        res = append(res, i)
    }

    return res
}

我不知道Gin是否有内置函数可以执行类似上述操作的功能。

英文:

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

huangapple
  • 本文由 发表于 2022年7月24日 20:47:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/73098522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定