Search code examples
httpgoquery-stringgo-gin

How to extract comma separated values from query parameter in Go?


I am using the Gin Web Framework and I am trying to find a way to bind a list of comma separated values from a query parameter into a struct. The following is a snippet of my code:

type QueryParams struct {
    Type            []string `form:"type"`
}


func BulkRead(c *gin.Context) {

    params := QueryParams{
        Type:            []string{},
    }

    if err := c.ShouldBindQuery(&params); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "couldn't bind query params"})
        return
    }
    
    c.Status(200)
}

Request: GET /api/v1/car?type=ford,audi

What I expect: ["ford", "audi"]

What I am getting: "ford,audi"

Is there an easy way to do this? Or will I need to write a custom function to handle this?


Solution

  • There may not be such a way. Usually I do this:

    type QueryParams struct {
        Type string `form:"type"`
    }
    
    func (q *QueryParams) Types() []string {
        return strings.Split(q.Type, ",")
    }
    
    func BulkRead(c *gin.Context) {
        params := new(QueryParams)
    
        if err := c.ShouldBindQuery(&params); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "couldn't bind query params"})
            return
        }
        c.JSONP(200, map[string]interface{}{
            "types": params.Types(),
        })
    }