Validate Gin JSON input with `ShouldBindJSON` and binding tags
Gin's ShouldBindJSON reads a request body into a Go struct, checks its binding tag rules, and returns any error to the caller. Use it instead of BindJSON when you want to control the client error response. This guide follows the current Gin binding APIs to validate JSON shape and required fields without exposing raw implementation details.
Gin's ShouldBindJSON reads a request body into a Go struct, checks its binding tag rules, and returns any error to the caller. Use it instead of BindJSON when you want to control the client error response. This guide follows the current Gin binding APIs to validate JSON shape and required fields without exposing raw implementation details.
Define the request type and validation rule
Use json tags for input names and binding tags for validation. The example requires a project name and limits it to 80 characters. Gin uses the tag syntax of go-playground/validator.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type CreateProjectRequest struct {
Name string `json:"name" binding:"required,max=80"`
}
func main() {
router := gin.Default()
router.POST("/projects", func(c *gin.Context) {
var input CreateProjectRequest
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_request",
"message": "body must be JSON with a non-empty name of at most 80 characters",
})
return
}
c.JSON(http.StatusCreated, gin.H{"name": input.Name})
})
if err := router.Run(":8080"); err != nil {
panic(err)
}
}ShouldBind and Bind behave differently
ShouldBindJSON returns binding or validation errors so the handler can choose the status, JSON shape, and public message. BindJSON instead aborts handling and writes a 400 response on error. Trying to change the status afterward may produce a warning because headers were already written. Choose the ShouldBind family when you need control over the response.
ShouldBind selects a binder from Content-Type; ShouldBindJSON explicitly requires JSON. The latter makes a JSON API contract clear. Binding maps input and checks tags, but does not replace authorization or business-rule checks such as duplicate names or permission to create a project.
Return a safe, stable error
The example maps parse and field-validation errors to one 400 response and does not return err.Error() directly. Library error strings can contain input or implementation details. If a production API needs field-level errors, classify validation error types and map only approved field names and stable error codes.
The example returns 201 only after validation. It has no persistence layer, so it does not actually create data; the success response only illustrates the flow. A real API should base its response on completed persistence and the created resource identifier.
Verify locally
Configure Gin in the project, save the file as main.go, and run go run .. Posting valid JSON {"name":"Notes"} to http://localhost:8080/projects should return 201 and JSON containing the name. An empty name, a name longer than 80 characters, or malformed JSON should return 400 with invalid_request. These are expected results; the code was not compiled or run here.
If invalid input passes, check the struct tags and binding rule, and confirm the request body and Content-Type are JSON. Ensure the error branch returns so the handler does not write another response after the 400.
Official sources
[Gin binding overview](https://gin-gonic.com/en/docs/binding/)
[Gin model binding and validation](https://gin-gonic.com/en/docs/binding/binding-and-validation/)
[Gin middleware and default router behavior](https://gin-gonic.com/en/docs/middleware/using-middleware/)
[Gin v1.12.0 release announcement](https://gin-gonic.com/en/blog/news/gin-1-12-0-release-announcement/)