Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Routing and Handlers

Responses in Gin: JSON, XML, Text, Files and Headers

Send responses from Gin handlers with c.JSON, IndentedJSON, PureJSON, XML, YAML, String, Data, File and Status; set headers and cookies, shape JSON with struct tags and negotiate content.

A handler's job ends when it has written a response. Gin offers a method for each common format, and they all work the same way: they set the Content-Type header, write the status code, and encode the body. This lesson tours them, shows how Go struct tags control JSON, and explains content negotiation. It continues from Path and Query Parameters.

c.JSON and gin.H

The workhorse is c.JSON(status, value). The value can be a gin.H map, a struct, a slice, or anything encoding/json can marshal:

Go
type Product struct {
	ID    int     `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

r.GET("/product", func(c *gin.Context) {
	c.JSON(http.StatusOK, Product{ID: 7, Name: "Notebook", Price: 4.5})
})

r.GET("/status", func(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"ok": true, "items": []string{"a", "b"}})
})

Prefer structs for responses. They give you a stable, documented shape and a compile-time check of field names. gin.H is best for tiny ad hoc bodies such as {"error": "..."}.

Shaping JSON with struct tags

The json tag controls the field name and behavior. Gin uses the standard encoding/json rules by default:

Go JSON struct tags: names, omitempty and hiding fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three habits to take from this: use json:"-" for secrets (or better, return a separate response struct without them), initialize slices to []string{} when clients expect [] instead of null, and use omitempty for optional fields. Binding JSON and Forms uses the same tags for the request direction.

Other JSON flavors

Method Difference
c.IndentedJSON Pretty-printed with indentation. Convenient for debugging, wasteful in production
c.PureJSON Does not escape <, > and & as <, so HTML in strings stays readable
c.AsciiJSON Escapes all non-ASCII characters as \uXXXX
c.SecureJSON Prefixes arrays with while(1); to defend old browsers against JSON hijacking
c.JSONP Wraps the JSON in a callback function; legacy, avoid

Plain c.JSON escapes HTML characters, which surprises people who return markup. The difference is the SetEscapeHTML switch on the standard encoder:

Go Why PureJSON exists: HTML escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both outputs are valid JSON that decodes to the same string; the escaped form is simply safer when the JSON is embedded in an HTML page.

XML, YAML and text

Go
r.GET("/p.xml", func(c *gin.Context) { c.XML(http.StatusOK, Product{ID: 7, Name: "Notebook"}) })
r.GET("/p.yaml", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"name": "Notebook"}) })
r.GET("/hello", func(c *gin.Context) { c.String(http.StatusOK, "Hello, %s!", "world") })

c.String takes a format string, like fmt.Sprintf. For XML you can add xml struct tags, such as xml:"name,attr". c.TOML and c.ProtoBuf exist as well.

Raw bytes, files and downloads

Go
r.GET("/logo.svg", func(c *gin.Context) {
	c.Data(http.StatusOK, "image/svg+xml", svgBytes)
})
r.GET("/report", func(c *gin.Context) {
	c.File("./reports/2025.pdf") // serves the file, detects its type
})
r.GET("/download", func(c *gin.Context) {
	c.FileAttachment("./reports/2025.pdf", "annual-report.pdf") // forces a download
})

c.File serves a file from disk and handles Range requests and conditional headers for you. Never pass a user-supplied path directly to it; the static files chapter explains the path-traversal rules.

Status, headers and cookies

Go
r.POST("/items", func(c *gin.Context) {
	c.Header("Location", "/items/9")            // response header
	c.Header("Cache-Control", "no-store")
	c.SetCookie("seen", "1", 3600, "/", "", true, true) // name, value, maxAge, path, domain, secure, httpOnly
	c.Status(http.StatusCreated)                // status only, no body yet
	c.JSON(http.StatusCreated, gin.H{"id": 9})
})

Set headers before writing the body: once the body starts, the headers are already sent. c.Status records the status without writing, which helps when middleware sets a status before the handler writes. For HttpOnly, Secure and SameSite cookie settings, see the security chapter; cookies that carry sessions must be HttpOnly and Secure.

Content negotiation

Clients tell you which format they want through the Accept header. Gin can pick for you with c.Negotiate, or you can switch yourself:

Go
c.Negotiate(http.StatusOK, gin.Negotiate{
	Offered: []string{gin.MIMEJSON, gin.MIMEXML},
	Data:    product,
})

This stand-in negotiates between JSON and XML by hand, so you can see how little is involved:

Go Stand-in: choosing JSON or XML from the Accept header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Streaming and server-sent events

For long-lived responses Gin provides c.Stream and c.SSEvent, which write chunks and flush them to the client as you go. Use them for progress feeds and live updates:

Go
r.GET("/events", func(c *gin.Context) {
	for i := 1; i <= 3; i++ {
		c.SSEvent("tick", i)
		c.Writer.Flush()
		time.Sleep(time.Second)
	}
})

Remember to stop when the client disconnects: check c.Request.Context().Done() inside your loop.

A consistent error shape

Pick one error format and use it everywhere, so API clients can handle failures uniformly:

Go
type ErrorBody struct {
	Error string `json:"error"`
	Code  string `json:"code,omitempty"`
}

c.JSON(http.StatusNotFound, ErrorBody{Error: "book not found", Code: "book_not_found"})

Do not leak internals (SQL text, stack traces) in this body in production. Gin Modes shows how to vary detail by mode.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method returns JSON without escaping < and > as unicode escapes?

    PureJSON turns off HTML escaping, so markup inside strings stays readable.
  2. 2. What does the struct tag json:"-" do?

    A dash tells encoding/json to skip the field, which is useful for password hashes and internal data.
  3. 3. Why should headers be set before writing the body?

    Once the first bytes of the body are written, the status line and headers are already on the wire.
  4. 4. Which method forces the browser to download a file under a chosen name?

    FileAttachment sets Content-Disposition: attachment with the file name you provide.
  5. 5. A nil slice field with tag json:"tags" is encoded as what?

    A nil slice becomes null. Initialize it to an empty slice if clients expect [].

Summary

  • c.JSON(status, value) is the main response method; prefer structs, use gin.H for tiny bodies.
  • Struct tags control names, omitempty and hidden fields; initialize slices to avoid null.
  • PureJSON, IndentedJSON, AsciiJSON and SecureJSON vary escaping and formatting.
  • c.XML, c.YAML, c.String, c.Data, c.File and c.FileAttachment cover other formats and downloads.
  • Set headers and cookies before the body; use c.Status to set only the status.
  • c.Negotiate (or a manual Accept check) serves several formats from one handler.
  • Use a single error shape and never leak internals.

Next: Redirects and Custom 404 Pages handles requests that do not match anything.