Gin JSON Binding: Struct vs Map
In this tutorial, you'll learn about Gin JSON Binding: Struct vs Map. We cover key concepts, practical examples, and best practices.
JSON binding in Gin -- Bind request bodies correctly using ShouldBindJSON or ShouldBindWith to handle different content types.
The Problem
c.BindJSON() and c.ShouldBindJSON() require Content-Type application/json. If the client sends a different Content-Type, binding fails silently. Always check the binding error.
Wrong
func createUser(c *gin.Context) {
var input struct {
Name string `json:"name"`
Age int `json:"age"`
}
c.ShouldBindJSON(&input)
c.JSON(200, input)
}
Output:
$ curl -X POST http://localhost:8080/users -H "Content-Type: text/plain" -d '{"name":"John"}'
{"name":"John","age":0}
Right
func createUser(c *gin.Context) {
var input struct {
Name string `json:"name" binding:"required"`
Age int `json:"age"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(200, input)
}
Output:
$ curl -X POST http://localhost:8080/users -d 'invalid json'
{"error":"invalid character 'i' looking for beginning of value"}
Prevention
- Always check error from ShouldBindJSON
- Use c.ShouldBindWith(&obj, binding.Query) for GET parameters
- Use c.ShouldBindUri(&obj) for URI parameters
- Set explicit Content-Type validation before binding
- Use struct field tags for validation: binding:"required"
Common Mistakes with gin bound json
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro