3

I'm trying to send a post request with form data and bind it to a nested slice.

Here's a minimal example:

type House struct {
    Rooms []Room `form:"rooms"`
}

type Room struct {
    NumberOfDoors int `form:"numberofdoors"`
}

func main() {
    r := gin.Default()
    r.POST("/", func(c *gin.Context) {
        var house House
        if err := c.ShouldBindWith(&house, binding.FormPost); err != nil {
            c.String(http.StatusBadRequest, "bind error: %v", err)
            return
        }
        c.JSON(http.StatusOK, house)
    })
    _ = r.Run(":8080")
}

Am I right to believe that something like this should be possible?

curl -i -H 'Content-Type: application/x-www-form-urlencoded' \
  --data 'rooms[0].numberofdoors=1' \
  http://localhost:8080/
2
  • Afaik, you can't use slices (just maps and arrays). But why not use JSON directly? Declare Rooms using json:"rooms" binding:"required" and NumberOfDoors using json:"numberofdoors" binding:"required". Then check with if err := c.ShouldBindJSON(&house); err != nil {…}, and use curl -i -H 'Content-Type: application/json' -d '{"rooms":[{"numberofdoors":1},{"numberofdoors":2}]}' http://localhost:8080/ for testing. Commented Oct 14 at 15:20
  • 1
    @pmf I guess it is not that straightforward to use JSON directly if the request comes from a <form> without cluttering the code with javascript. Commented Oct 15 at 8:49

0

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.