0Pricing
Go Academy · Lesson

Request Binding and Validation

ShouldBindJSON, binding tags, and validator

Request Binding and Validation is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Query binding

Bind query string parameters to a struct with c.ShouldBindQuery:

type ListRequest struct {
    Page  int `form:"page"  binding:"gte=1"`
    Limit int `form:"limit" binding:"gte=1,lte=100"`
}
var q ListRequest
c.ShouldBindQuery(&q)

Path parameter binding

Bind path parameters to a struct with c.ShouldBindUri:

type IDParam struct {
    ID int64 `uri:"id" binding:"required,gt=0"`
}
var p IDParam
c.ShouldBindUri(&p)

Validation tags

Gin uses github.com/go-playground/validator/v10. Common tags: required, email, min, max, gte, lte, len, oneof.

Custom validators

Register a custom validation function with binding.Validator.Engine():

validate := binding.Validator.Engine().(*validator.Validate)
validate.RegisterValidation("username", validateUsername)

Validation error response

Parse validator errors into a user-friendly response with field names and messages:

var ve validator.ValidationErrors
if errors.As(err, &ve) {
    errs := make([]string, len(ve))
    for i, e := range ve {
        errs[i] = fmt.Sprintf("%s: %s", e.Field(), e.Tag())
    }
    c.JSON(400, gin.H{"errors": errs})
}

Multipart form files

Handle file uploads with c.FormFile:

file, _ := c.FormFile("avatar")
c.SaveUploadedFile(file, "./uploads/"+file.Filename)

Content-Type negotiation

Gin's ShouldBind chooses the binding based on Content-Type automatically (JSON for application/json, form for application/x-www-form-urlencoded).

Max request body size

Limit the request body size to prevent memory exhaustion:

r.MaxMultipartMemory = 8 << 20 // 8 MiB for multipart

Nested struct validation

Validation runs recursively on nested structs. Use dive to validate slice elements:

Tags []string `json:"tags" binding:"required,dive,min=1,max=30"`

Quick Check

What is the difference between c.ShouldBindJSON and c.BindJSON in Gin?

Recap: Request Binding

Key points:

  • ShouldBindJSON/ShouldBindQuery/ShouldBindUri for typed binding
  • binding:"required,email,gte=0" tags via go-playground/validator
  • Custom validators via binding.Validator.Engine()
  • Parse ValidationErrors for field-level error messages

Frequently asked questions

Is the “Request Binding and Validation” lesson free?

Yes — the full text of “Request Binding and Validation” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Request Binding and Validation”?

ShouldBindJSON, binding tags, and validator You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Request Binding and Validation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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