Never Trust the Client
Imagine you run a small shop with a suggestion box by the door. You'd expect notes like "Please stock more oat milk." What you'd also get, eventually, is a note that says "DROP TABLE customers," a note written in an unbroken wall of 40,000 characters, and a note that is somehow also a live frog. Every public door invites the full range of human creativity, and your API's doors are about as public as doors get.
This is the philosophy behind a single, tattoo-worthy rule of backend development: never trust the client. Not the browser. Not your own frontend. Not the mobile app you wrote last month. Anything that arrives over the network is guilty of being weird until proven otherwise.
In this article we'll cover how to validate input in Go and Gin, the difference between validation and sanitization, how to defend against the classic injection attacks, and how to give users error messages that help rather than mystify.
Why "my frontend already checks it" isn't a defense
Your JavaScript form might beautifully refuse an empty email. But that check lives in the browser, on a machine you don't control. Anyone can open the dev tools, use curl, write a script, or use a tool like Postman to send whatever they like directly to your API, skipping your form entirely.
Frontend validation is for user experience: instant feedback, no round trip. Backend validation is for security and correctness: the one that actually protects you. You need both, but only one of them is a lock. The other is a friendly "Wet Paint" sign.
Validation vs sanitization: two different jobs
People use these words interchangeably, but they do different things.
Validation asks: is this input acceptable? If not, reject it. "Age must be between 0 and 130." "Email must look like an email." The input either passes or gets sent back with an error.
Sanitization asks: can I clean this input into something safe? Trim whitespace, normalize casing, strip control characters. The input is adjusted and accepted.
A good rule of thumb: validate strictly, sanitize gently, and prefer rejecting over silently rewriting. If a username arrives as " amina ", trimming the spaces is harmless sanitization. If it arrives as "<script>alert(1)</script>", quietly "cleaning" it into something else can cause surprises. Often the right answer is to reject it and say why.
And one more principle worth memorizing: prefer an allowlist over a blocklist. Defining what's permitted ("letters, digits, and underscores, 3 to 20 characters") is far safer than trying to list everything forbidden. The universe of bad input is infinite. The universe of acceptable input is usually small and describable.
Step one: limit the size of the request
Before checking what the input says, check how much of it there is. An attacker, or a buggy client, might send a 2 GB JSON body and see how your server copes. Cap it:
func LimitBody(maxBytes int64) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
c.Next()
}
}
// in setup
r.Use(LimitBody(1 << 20)) // 1 MB
Now any request body beyond 1 MB triggers an error when your handler tries to read it. For most JSON APIs, that's plenty. Raise it for specific routes like file uploads, and only those.
Also consider timeouts on your http.Server (ReadTimeout, ReadHeaderTimeout) so slow clients can't hold connections open forever, a trick known as Slowloris. A server without timeouts is a shop where one person can stand in the doorway for eternity.
Step two: structural validation with binding tags
Gin uses the go-playground/validator library under the hood. You attach rules to struct fields with binding tags:
type RegisterRequest struct {
Email string `json:"email" binding:"required,email,max=254"`
Password string `json:"password" binding:"required,min=8,max=72"`
Name string `json:"name" binding:"required,min=1,max=100"`
Age int `json:"age" binding:"gte=13,lte=130"`
}
Then in the handler:
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
respondValidationError(c, err)
return
}
If any rule fails, ShouldBindJSON returns an error describing what went wrong. Some tags you'll use constantly:
-
required: the field must be present and non-zero -
email,url,uuid: format checks -
min,max: length for strings, value for numbers -
gte,lte: greater or less than or equal -
oneof=admin member guest: an allowlist of values -
alphanum: letters and digits only -
dive: apply the following rules to each element of a slice
A classic trap: zero values
Suppose a field is optional, and 0 is a legitimate value, such as quantity or discount. With a plain int, required fails for a legitimate 0, because zero is Go's "empty." The cure is a pointer:
type UpdateStockRequest struct {
Quantity *int `json:"quantity" binding:"required,gte=0"`
}
With *int, a missing field is nil (rejected by required), but an explicit 0 is a real value that passes. It's the difference between a blank form and a form where someone wrote "0."
Step three: turning validator errors into friendly messages
By default, a validation failure produces text like Key: 'RegisterRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag. That's helpful to nobody. Translate it into something a frontend can display next to the right field:
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}
func respondValidationError(c *gin.Context, err error) {
var verrs validator.ValidationErrors
if errors.As(err, &verrs) {
out := make([]FieldError, 0, len(verrs))
for _, fe := range verrs {
out = append(out, FieldError{
Field: strings.ToLower(fe.Field()),
Message: messageFor(fe),
})
}
c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": out})
return
}
// malformed JSON, wrong types, etc.
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
}
func messageFor(fe validator.FieldError) string {
switch fe.Tag() {
case "required":
return "this field is required"
case "email":
return "must be a valid email address"
case "min":
return "is too short (minimum " + fe.Param() + ")"
case "max":
return "is too long (maximum " + fe.Param() + ")"
default:
return "is invalid"
}
}
Now the client receives:
{
"errors": [
{ "field": "email", "message": "must be a valid email address" },
{ "field": "password", "message": "is too short (minimum 8)" }
]
}
Your frontend can highlight both fields at once. Returning all the problems in one go beats the maddening experience of fixing one error, resubmitting, and discovering the next. And for the HTTP status: 400 for "I couldn't even parse this," 422 for "I understood it, but it's not acceptable," are a widely used and sensible split.
Step four: meaning-level validation in the service
Struct tags check shape. They can't check meaning. "Is this coupon still valid?" "Does this product exist?" "Is the end date after the start date?" Those need data and rules, so they belong in the service layer, as we saw earlier.
A neat division:
- Handler: is the JSON well-formed, and do the fields have the right types, lengths, and formats?
- Service: does this make sense in the real world?
And don't forget the cross-field checks that tags can't easily express:
if !req.EndDate.After(req.StartDate) {
return &domain.ValidationError{Field: "end_date", Message: "must be after start_date"}
}
SQL injection: the evergreen attack
An attacker enters this as their username:
' OR '1'='1
If your code builds queries by gluing strings together, it ends up like this:
// DANGEROUS
query := "SELECT * FROM users WHERE name = '" + name + "'"
...and the database sees WHERE name = '' OR '1'='1', which is always true. Now it returns every user. Variants of this trick have drained real databases for decades.
The defense is not clever filtering. It's parameterized queries, which send the SQL and the values separately so the database never confuses data for commands:
// Safe with GORM
db.Where("name = ?", name).First(&user)
// Safe with database/sql
db.QueryRowContext(ctx, "SELECT id FROM users WHERE name = $1", name)
The golden rule: never build SQL with string concatenation or fmt.Sprintf using user input. There's one stubborn exception: values that can't be parameterized, such as column names for sorting. For those, use an allowlist:
allowedSort := map[string]string{
"newest": "created_at DESC",
"price": "price ASC",
}
orderBy, ok := allowedSort[req.Sort]
if !ok {
orderBy = "created_at DESC"
}
db.Order(orderBy).Find(&products)
The client sends a key. Your code picks the SQL. The client never writes a single character of it.
XSS: when your output bites back
Cross-site scripting happens when user-supplied text is displayed on a page and the browser interprets it as code. Suppose a user sets their display name to <script>stealCookies()</script> and your frontend inserts it into the page with innerHTML. Everyone who views that profile runs the attacker's script.
The defense here lives mostly on the output side, since the same text is safe in a database and dangerous in HTML:
- In your vanilla JavaScript frontend, use
textContentinstead ofinnerHTMLwhen inserting user data.textContenttreats everything as plain text.
// Safe
nameEl.textContent = user.name;
// Dangerous with user data
nameEl.innerHTML = user.name;
- If you must render HTML (say, rich-text posts), use a well-tested sanitizer library, not a homemade regex.
- If your Go backend renders HTML templates,
html/templateescapes output automatically. Never usetext/templatefor HTML, and avoid marking untrusted values as trusted. - Add a Content-Security-Policy header as a second layer of defense.
Notice that the correct protection isn't "strip angle brackets from input." A user might legitimately be named O'Brien, or write a post about <div> tags. Escape at the point of use, according to where the data is going: HTML, SQL, a URL, a shell command. Each destination has its own dangerous characters.
Mass assignment: letting users set fields they shouldn't
Here's a quiet, nasty bug. Your User model has an IsAdmin field. Your update handler binds the request directly onto the model:
var user domain.User
c.ShouldBindJSON(&user) // client can send {"is_admin": true}
db.Save(&user)
A curious user adds "is_admin": true to their profile update. Congratulations, you've built a self-service promotion system.
The fix: bind to dedicated request structs that contain only the fields a client may set. That's exactly why we separate RegisterRequest from domain.User. The request struct is an allowlist by construction. If a field isn't in it, the client can't touch it.
File uploads and paths
Uploads deserve extra suspicion:
-
Never trust the filename. A name like
../../etc/passwdis a path traversal attempt. Generate your own filenames (a UUID plus a safe extension) and ignore the client's. -
Never trust the declared content type. Check the actual bytes with
http.DetectContentType, and allowlist formats. - Cap the file size, and store uploads outside your executable web root.
- Don't serve uploaded files from the same origin as your app if they could contain active content.
Normalize before you compare
Subtle bugs hide in text. Amina@Example.com and amina@example.com are the same email in practice, but different strings. If you don't normalize, two "different" accounts exist and password resets go to the wrong place. Decide your rules, trim, lowercase emails, and apply them everywhere, ideally in one function:
func NormalizeEmail(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}
Unicode adds more flavors of trouble: lookalike characters, invisible zero-width characters, and strings where "length" depends on whether you count bytes or characters. For things like usernames, a restrictive allowlist (ASCII letters, digits, underscore) sidesteps a whole category of mischief.
Defensive details that pay off
-
Clamp pagination.
limitshould have a default and a maximum, say 20 and 100. Nobody needs a million rows in one response. -
Validate IDs. A path parameter is a string. Parse it, check it, handle
banana. - Limit nested depth and array lengths where relevant. A JSON array with 5 million elements is a denial of service dressed as a request.
-
Be careful with regular expressions on user input. A badly written pattern can take exponential time on certain strings (ReDoS). Go's
regexppackage uses a linear-time engine, which helps, but keep patterns simple anyway. -
Reject unknown fields when strictness matters:
decoder.DisallowUnknownFields()catches typos and probing.
Common mistakes
Relying only on frontend validation. It's a convenience, not a defense.
String-built SQL. Parameterize, always, and allowlist anything that can't be a parameter.
Binding straight onto database models. Use request structs. Mass assignment is real.
Rewriting input silently. Prefer clear rejection over mysterious "cleaning."
Returning cryptic validator messages. Translate them into field-level guidance.
Escaping on input instead of output. Store raw (validated) text, and escape for each destination when you use it.
Forgetting size limits. Cap bodies, strings, arrays, and page sizes.
Quick recap
- Never trust the client. Validate on the server, no matter what the frontend does.
- Validate strictly with allowlists, and sanitize gently with trimming and normalization.
- Cap request sizes and set server timeouts.
- Use
bindingtags for shape, services for meaning, and pointers when zero is a valid value. - Return all field errors together in a clear, consistent format.
- Parameterize every SQL query, escape output for its destination, and use
textContentinstead ofinnerHTML. - Bind to dedicated request structs to avoid mass assignment.
- Treat uploads, filenames, and paths as hostile until proven otherwise.
Top comments (0)