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/
Roomsusingjson:"rooms" binding:"required"andNumberOfDoorsusingjson:"numberofdoors" binding:"required". Then check withif err := c.ShouldBindJSON(&house); err != nil {…}, and usecurl -i -H 'Content-Type: application/json' -d '{"rooms":[{"numberofdoors":1},{"numberofdoors":2}]}' http://localhost:8080/for testing.