Skip to content

Binding

Gin provides a powerful binding system that parses request data into Go structs and validates it automatically. Instead of manually calling c.PostForm() or reading c.Request.Body, you define a struct with tags and let Gin do the work.

Bind vs ShouldBind

Gin offers two families of binding methods:

MethodOn errorUse when
c.Bind, c.BindJSON, etc.Calls c.AbortWithError(400, err) automaticallyYou want Gin to handle error responses
c.ShouldBind, c.ShouldBindJSON, etc.Returns the error for you to handleYou want custom error responses

In most cases, prefer ShouldBind for more control over error handling.

Quick example

type LoginForm struct {
User string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
var form LoginForm
// ShouldBind checks Content-Type to select a binding engine automatically
if err := c.ShouldBind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "logged in"})
})
router.Run(":8080")
}

Supported formats

Gin can bind data from many sources: JSON, XML, YAML, TOML, form data (URL-encoded and multipart), query strings, URI parameters, and headers. Use the appropriate struct tag (json, xml, yaml, form, uri, header) to map fields. Validation rules go in the binding tag and use go-playground/validator syntax.

In this section