0PricingLogin
Go Academy · Lesson

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

  1. Gin Router and Route Groups
  2. Request Binding and Validation
  3. Response Helpers and Status Codes
  4. Gin Middleware: Auth and Logging
← Back to Go Academy