Request Binding and Validation
ShouldBindJSON, binding tags, and validator
Binding request body
Gin can bind JSON, XML, form data, and query strings to Go structs using the binding struct tag and c.ShouldBind* functions:
type CreateUserRequest struct {
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email"`
Age int `json:"age" binding:"gte=0,lte=150"`
}
func createUser(c *gin.Context) {
var req CreateUserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
}ShouldBind vs MustBind
ShouldBind* returns the error for you to handle. Bind* (Must variant) automatically writes a 400 response and aborts on error — use ShouldBind for custom error responses.
All lessons in this course
- Gin Router and Route Groups
- Request Binding and Validation
- Response Helpers and Status Codes
- Gin Middleware: Auth and Logging