Go Academy · Lesson

Request Binding and Validation

ShouldBindJSON, binding tags, and validator

Lesson 2 of 413 steps

Request Binding and Validation is a free Go Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Request Binding and Validation” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Request Binding and Validation”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

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