Go services · 3 MIN READ

Validate a request before doing side effects

Follow JSON binding, size limits, validation and a safe error response.

Decoded JSON is not yet trusted application input. A field can have the right Go type and still violate a business rule. Bound the body, handle decoding failure, then apply domain validation before writing to storage or calling another service.

01

Separate decoding from application rules

This adapter accepts a JSON object with a non-empty name. ShouldBindJSON lets the handler choose its error response instead of relying on an automatically written status. The body cap is a policy example and should match the endpoint.

go
type CreateItem struct {
    Name string `json:"name" binding:"required,max=80"`
}
func create(c *gin.Context) {
    c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10)
    var input CreateItem
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
        return
    }
    // Normalize and validate domain rules before persisting input.
}
Read the code

The generic error avoids echoing an arbitrary decoder message. A production API can map an over-limit body to 413 and expose structured, documented field errors. Decide whether unknown JSON fields should be rejected and configure that policy deliberately.

02

Validation does not provide authorization

A valid item ID does not prove the requester may access that item. Authenticate the caller, check authorization at the relevant boundary, and keep secrets out of logs and responses. Binding tags check specified shapes; business invariants may require several fields and current state.

03

Test the cases users actually send

Cover missing fields, wrong types, malformed and oversized input, duplicate requests and unexpected fields according to the chosen policy. Specify whether optional zero values differ from missing values. If accepting a command has an external effect, consider an idempotency contract rather than assuming retries are harmless.

TAKE THIS WITH YOU

Decode, validate shape, enforce business rules and authorization, then perform side effects. Each step has a different responsibility.

Check your understanding

Which statement is correct about successful json binding?

Go to the source

Progress stays in this browser. No account needed.