Around Go: Gin services · 3 MIN READ
Gin input: size limits, binding and business validation are separate
Reject oversized or invalid input before performing a business side effect.
Binding converts a request into a Go value. It does not prove authorization or a business invariant, and it does not by itself impose your desired body-size budget. A robust handler limits input first, chooses whether errors are returned or immediately written, validates normalized values and only then calls the use case. Return one deliberate response instead of letting several layers compete to write it.
gin · A MAP OF THE IDEA
- Limit bytes
- Bind DTO
- Validate + authorize
- Call use case
Useful when
- Reject oversized or invalid input before performing a business side effect.
- Makes the owner and the failure boundary explicit.
Watch out
- BindJSON may abort and write a response automatically; trying to overwrite it later can produce the wrong status or duplicate output.
- Run native service and failure tests in your own development environment.
Implementation & operation cost: Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.
The contract and the failure
Binding converts a request into a Go value. It does not prove authorization or a business invariant, and it does not by itself impose your desired body-size budget. A robust handler limits input first, chooses whether errors are returned or immediately written, validates normalized values and only then calls the use case. Return one deliberate response instead of letting several layers compete to write it.
Work through the example
Select binders explicitly when input sources matter, and distinguish optional, zero and null values in the DTO. Check a second decode for trailing JSON and reject unknown fields when the API contract requires strict JSON; a single successful binder call does not establish those stronger properties. Gin’s decoder options are process-wide configuration and should be set before concurrent serving, not toggled per request.
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/gin-gonic/gin"
)
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.POST("/notes", func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1024)
var in struct {
Title string `json:"title" binding:"required,max=80"`
}
if err := c.ShouldBindJSON(&in); err != nil {
var large *http.MaxBytesError
if errors.As(err, &large) {
c.AbortWithStatus(413)
} else {
c.AbortWithStatus(400)
}
return
}
title := strings.TrimSpace(in.Title)
if title == "" {
c.AbortWithStatus(400)
return
}
c.JSON(201, gin.H{"title": title})
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/notes", strings.NewReader(`{"title":" "}`)))
fmt.Println(w.Code) // 400, before any write to storage
}MaxBytesReader supplies a 1 KiB input budget. ShouldBindJSON returns the error so this handler owns the response. The whitespace-only title can pass a required tag, so normalization and the business rule still reject it. The example returns a small error response and never echoes parser internals or secret request content.
Production decisions
BindJSON may abort and write a response automatically; trying to overwrite it later can produce the wrong status or duplicate output. Validation tags do not check ownership of a referenced object and do not make arbitrary SQL safe. Test malformed JSON, oversized input, whitespace, omitted fields, trailing values, unknown fields and unauthorized resource IDs as distinct cases.
Explain it in an interview
A title contains only spaces and has a required tag. Is the business input necessarily valid? No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.
TAKE THIS WITH YOU
Reject oversized or invalid input before performing a business side effect. No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts.
Check your understanding
A title contains only spaces and has a required tag. Is the business input necessarily valid?
Go to the source
Progress stays in this browser. No account needed.