Gin foundations · 5 MIN READ

Gin JSON responses: know what each renderer writes and return a DTO, never your storage model

Choose between c.JSON, PureJSON, IndentedJSON, SecureJSON and AsciiJSON by their exact output, set status codes deliberately and render a response DTO with correct omitempty and omitzero tags.

The bytes a handler writes are a public contract: field names, which fields exist, how characters are escaped, the Content-Type and the status. Gin has five JSON renderers that look interchangeable and are not, and c.JSON will happily publish every field of whatever struct you hand it, including the ones you add next year.

gin · A MAP OF THE IDEA

  1. Map model to DTO
  2. Tag omit rules per field
  3. Pick renderer by bytes
  4. Assert status and body

Useful when

  • A DTO makes every published field a reviewed decision.
  • c.JSON output is HTML-safe and has a stable Content-Type.

Watch out

  • Marshal errors and repeated renders leave the first status in place.
  • AsciiJSON mis-encodes characters above U+FFFF.

Implementation & operation cost: One DTO type and mapping function per resource, plus contract tests; mapping is cheap compared with an accidental data leak.

01

Rendering is where internal state leaks

All of Gin's JSON renderers start from the configured codec, which is encoding/json unless the binary is built with the jsoniter, go_json or sonic tags. encoding/json exports every exported field, using the Go field name when there is no tag. Rendering a storage struct therefore couples the API to the schema: renaming a column renames a JSON key, and adding a field such as PasswordHash or an internal flag publishes it immediately. A separate response type, a DTO, is the boundary where you decide what leaves the process.

02

Ten responses side by side

The program renders the same small value with each JSON renderer, then contrasts a storage struct with its DTO, and finishes with two cases where Gin drops the body. Newlines in bodies are printed as \n so you can see exactly where each renderer adds one.

go
package main

import (
	"fmt"
	"math"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// account is the storage model. It is never rendered directly.
type account struct {
	ID           int64
	Email        string
	PasswordHash string
	CreatedAt    time.Time
	UpdatedAt    time.Time
	DeletedAt    time.Time
}

// accountResponse is the public contract for GET /accounts/:id.
type accountResponse struct {
	ID        int64     `json:"id"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at,omitempty"` // omitempty never omits a struct
	DeletedAt time.Time `json:"deleted_at,omitzero"`  // omitzero uses time.Time.IsZero
}

func toResponse(a account) accountResponse {
	return accountResponse{ID: a.ID, Email: a.Email, CreatedAt: a.CreatedAt, UpdatedAt: a.UpdatedAt, DeletedAt: a.DeletedAt}
}

func main() {
	gin.SetMode(gin.TestMode)
	acct := account{
		ID:           7,
		Email:        "dev@example.com",
		PasswordHash: "$2a$10$not-a-real-hash",
		CreatedAt:    time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
	}
	text := gin.H{"note": "<b>R&D</b> café"}

	var lastErr string
	r := gin.New()
	r.Use(func(c *gin.Context) {
		c.Next()
		if len(c.Errors) > 0 {
			lastErr = c.Errors.Last().Error()
		}
	})
	r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, text) })
	r.GET("/pure", func(c *gin.Context) { c.PureJSON(http.StatusOK, text) })
	r.GET("/ascii", func(c *gin.Context) { c.AsciiJSON(http.StatusOK, text) })
	r.GET("/indented", func(c *gin.Context) { c.IndentedJSON(http.StatusOK, gin.H{"ok": true}) })
	r.GET("/secure-list", func(c *gin.Context) { c.SecureJSON(http.StatusOK, []int{1, 2}) })
	r.GET("/secure-object", func(c *gin.Context) { c.SecureJSON(http.StatusOK, gin.H{"ok": true}) })
	r.GET("/leaky", func(c *gin.Context) { c.JSON(http.StatusOK, acct) })
	r.GET("/accounts/7", func(c *gin.Context) { c.JSON(http.StatusOK, toResponse(acct)) })
	r.GET("/no-content", func(c *gin.Context) { c.JSON(http.StatusNoContent, gin.H{"dropped": true}) })
	r.GET("/nan", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ratio": math.NaN()}) })

	for _, path := range []string{
		"/json", "/pure", "/ascii", "/indented", "/secure-list", "/secure-object",
		"/leaky", "/accounts/7", "/no-content", "/nan",
	} {
		lastErr = ""
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
		body := strings.ReplaceAll(w.Body.String(), "\n", `\n`)
		if body == "" {
			body = "(empty body)"
		}
		fmt.Printf("%s %d [%s] %s\n", path, w.Code, w.Header().Get("Content-Type"), body)
		if lastErr != "" {
			fmt.Println("  c.Errors:", lastErr)
		}
	}
}
Read the code

c.JSON escapes <, > and & as \u003c, \u003e and \u0026 and leaves the UTF-8 é alone. PureJSON writes the characters literally and ends with \n, because it uses a json.Encoder. AsciiJSON also rewrites é as \u00e9 and sends Content-Type application/json without a charset. IndentedJSON uses four spaces. SecureJSON prefixes while(1); only to the array. /leaky shows Go field names and the password hash; the DTO uses snake_case tags, drops the hash, keeps the zero updated_at because omitempty never omits a struct, and drops deleted_at because omitzero asks time.Time.IsZero. The 204 body is discarded. The NaN cannot be marshaled, so Gin records the error in c.Errors, writes nothing, and the client receives 200 with an empty body.

03

Choose a renderer by its exact bytes

Use c.JSON by default: its HTML escaping makes the output safe to embed in a page and it adds no trailing newline. PureJSON is for clients that need literal characters, such as a payload that is signed or compared byte for byte; never embed its output in HTML. IndentedJSON costs bytes and CPU on every request, so keep it for debugging endpoints. SecureJSON defends against JSON hijacking in very old browsers by prefixing top-level arrays (the check is literally output that starts with [ and ends with ]); r.SecureJsonPrefix changes the prefix, and note that the method's doc comment says while(1), while the v1.12.0 default is while(1);. Returning an object at the top level avoids the issue and leaves room for pagination fields. AsciiJSON rewrites each non-ASCII rune with the format \u%04x, so characters above U+FFFF, which includes most emoji, come out as \u plus five hex digits, which a JSON parser reads as a different character followed by a digit. Do not use it for user-generated text.

04

Status codes and the bodies Gin drops

c.Status(code) records the status; with no body written, the response goes out empty when the chain finishes. For 1xx, 204 and 304, c.JSON writes the Content-Type header but discards the body, so c.Status(http.StatusNoContent) states the intent more honestly. c.Data(code, contentType, bytes) sends pre-encoded bytes and, since v1.12.0, sets Content-Length. In middleware, c.AbortWithStatusJSON stops the chain and answers in one call. Two failures are silent. A marshal error, from NaN, an infinity, a channel or a cycle, leaves a 200 with an empty body plus an entry in c.Errors, so an error middleware must check c.Errors as the errors-testing lesson does. A second render after the first one has written appends its body to the first and cannot change the status, so one function must own the response.

05

omitempty versus omitzero in a DTO

omitempty omits false, 0, "", nil pointers and interfaces, and slices, maps or strings of length zero; it never omits a struct, so a zero time.Time renders as 0001-01-01T00:00:00Z. omitzero, added in Go 1.24, omits a field when its type's IsZero method returns true or, without such a method, when the value is the zero value. That makes it right for time.Time and for value structs, but a non-nil empty slice is not a zero value, so omitzero keeps [] where omitempty drops it. With both options the field is omitted if either rule applies. Decide per field whether clients should see absent, null, zero or empty, and write that down in the tag.

go
type page struct {
	Items      []item    `json:"items"`                 // nil renders null: initialize to []item{}
	NextCursor string    `json:"next_cursor,omitempty"` // omitted on the last page
	Total      int       `json:"total,omitzero"`        // omitted when 0: is 0 a real answer?
	Generated  time.Time `json:"generated_at,omitzero"` // omitted when IsZero reports true
}
Read the code

This fragment annotates a pagination DTO. A nil Items slice encodes as null, which many clients mishandle, so initialize it to an empty slice. NextCursor disappears on the last page. Total with omitzero disappears when it is 0, which is wrong if zero is a meaningful count, so think before tagging numbers. Generated relies on time.Time.IsZero, which is exactly what omitzero consults.

06

Test the bytes, not just the status

For each endpoint assert the status, the Content-Type and the body. Decode the body into map[string]any and assert that sensitive keys such as password_hash are absent, because a struct-to-struct comparison cannot notice an extra field. Keep a golden file per DTO for contract review, and add one test that marshals every DTO with representative values, including floats from calculations, so a NaN fails in CI rather than as an empty 200 in production. If the JSON codec is swapped with build tags, run the same tests under that build.

TAKE THIS WITH YOU

Render DTOs with explicit tags, use c.JSON unless a renderer's exact bytes are required, and remember that a marshal error or a second render does not change the status already chosen.

Check your understanding

A DTO field is CreatedAt time.Time `json:"created_at,omitempty"` and the value is zero. What does encoding/json do?

Go to the source

Progress stays in this browser. No account needed.