Gin in the wider system · 6 MIN READ

Content negotiation in Gin: what NegotiateFormat really matches, 406 in your format and Vary: Accept

Serve JSON, CSV and HTML from one Gin handler with q-value-aware negotiation, a 406 that lists what is available, Vary: Accept for caches and a ?format= override where URLs must name the representation.

Content negotiation lets one URL return the representation each client prefers: JSON for an API client, CSV for a spreadsheet import, HTML for a browser. Gin offers c.NegotiateFormat and c.Negotiate for this, and reading their v1.12.0 source shows that they implement much less of the HTTP rules than their names suggest. The gaps are easy to close, but only once you know where they are.

gin · A MAP OF THE IDEA

  1. Check ?format= override
  2. Negotiate Accept by q
  3. Render or answer 406
  4. Send Vary: Accept

Useful when

  • One URL serves API clients, spreadsheets and browsers.
  • q-aware matching returns what clients actually asked for.

Watch out

  • Gin's NegotiateFormat ignores q-values and letter case.
  • c.Negotiate has no CSV branch and answers 406 with no body.
  • Vary: Accept fragments shared caches; prefer ?format= for links.

Implementation & operation cost: A small negotiation function with its tests, one renderer per representation, and lower CDN hit ratios on URLs that vary on Accept.

01

How Gin matches Accept, read from the source

parseAccept splits the header on commas, cuts each element at its first semicolon and trims spaces, so q-values and every other parameter are thrown away. NegotiateFormat caches that list in c.Accepted, which SetAccepted can replace, returns your first offer when the header is missing or empty, and panics if you pass no offers. Otherwise it walks the accepted entries in the client's order and compares each with your offers byte by byte: a * at the same position in either string matches the rest, and an accepted entry that is a prefix of an offer also matches, so even Accept: a selects application/json. Three consequences follow. Header order beats q: "application/json;q=0.1, text/csv" gets JSON. q=0 counts as acceptance: "text/csv;q=0, /" gets CSV, the one type the client excluded. And media types compare case-sensitively although RFC 9110 says they are case-insensitive, so "Application/JSON" matches nothing. c.Negotiate switches on that result for JSON, HTML, XML, YAML, TOML, ProtoBuf and BSON; any other offer, including text/csv and even text/xml, falls to the default branch, AbortWithError with 406, which commits the status with an empty body.

02

One handler, three representations, two negotiators

negotiate implements RFC 9110 section 12.5.1: each offer takes the q-value of the most specific media range that matches it, an exact type beating type/* and type/* beating /, q=0 excludes, the highest q wins and ties go to the server's order. The program prints Gin's choice and the RFC choice side by side for seven Accept headers, then sends seven requests through the real router, including a ?format= override and a call to c.Negotiate.

go
package main

import (
	"bytes"
	"cmp"
	"encoding/csv"
	"fmt"
	"html/template"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"

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

const mimeCSV = "text/csv"

// offers is the server's preference order; ties go to the earlier entry.
var offers = []string{binding.MIMEJSON, mimeCSV, binding.MIMEHTML}

// negotiate follows RFC 9110 section 12.5.1: each offer takes the q of the
// most specific range that matches it, q=0 excludes, the highest q wins.
func negotiate(accept string, offers []string) string {
	if strings.TrimSpace(accept) == "" {
		return offers[0] // no Accept means any type is acceptable
	}
	best, bestQ := "", 0.0
	for _, offer := range offers {
		q, specificity := 0.0, -1
		for part := range strings.SplitSeq(accept, ",") {
			mediaRange, params, _ := strings.Cut(part, ";")
			s := specificityOf(strings.ToLower(strings.TrimSpace(mediaRange)), offer)
			if s > specificity {
				specificity, q = s, qValue(params)
			}
		}
		if q > bestQ {
			best, bestQ = offer, q
		}
	}
	return best
}

// specificityOf ranks a match: exact type 2, type/* 1, */* 0, no match -1.
func specificityOf(mediaRange, offer string) int {
	switch {
	case mediaRange == offer:
		return 2
	case mediaRange == "*/*":
		return 0
	case strings.HasSuffix(mediaRange, "/*") && strings.HasPrefix(offer, mediaRange[:len(mediaRange)-1]):
		return 1
	}
	return -1
}

func qValue(params string) float64 {
	for p := range strings.SplitSeq(params, ";") {
		if v, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(p)), "q="); ok {
			q, err := strconv.ParseFloat(v, 64)
			if err != nil || q < 0 || q > 1 {
				return 0
			}
			return q
		}
	}
	return 1
}

type Row struct {
	Region string `json:"region"`
	Orders int    `json:"orders"`
}

var rows = []Row{{"eu-west", 1200}, {"us-east", 900}}

var formats = map[string]string{"json": binding.MIMEJSON, "csv": mimeCSV, "html": binding.MIMEHTML}

func report(c *gin.Context) {
	format := ""
	if f, ok := c.GetQuery("format"); ok {
		if format, ok = formats[f]; !ok { // the URL names the representation
			c.JSON(http.StatusBadRequest, gin.H{"error": "unknown_format", "formats": []string{"csv", "html", "json"}})
			return
		}
	} else {
		c.Header("Vary", "Accept") // the representation depends on Accept
		format = negotiate(c.GetHeader("Accept"), offers)
	}
	switch format {
	case binding.MIMEJSON:
		c.JSON(http.StatusOK, rows)
	case mimeCSV:
		var buf bytes.Buffer
		w := csv.NewWriter(&buf)
		w.Write([]string{"region", "orders"})
		for _, r := range rows {
			w.Write([]string{r.Region, strconv.Itoa(r.Orders)})
		}
		w.Flush()
		c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
	case binding.MIMEHTML:
		c.HTML(http.StatusOK, "report", rows)
	default:
		c.JSON(http.StatusNotAcceptable, gin.H{"error": "not_acceptable", "available": offers})
	}
}

func main() {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.SetHTMLTemplate(template.Must(template.New("report").Parse(
		`<table>{{range .}}<tr><td>{{.Region}}</td><td>{{.Orders}}</td></tr>{{end}}</table>`)))
	r.GET("/reports/sales", report)
	r.GET("/gin-negotiate", func(c *gin.Context) {
		c.Negotiate(http.StatusOK, gin.Negotiate{Offered: offers, Data: rows})
	})

	ginChoice := func(accept string) string {
		c, _ := gin.CreateTestContext(httptest.NewRecorder())
		c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
		if accept != "" {
			c.Request.Header.Set("Accept", accept)
		}
		return cmp.Or(c.NegotiateFormat(offers...), "(none)")
	}
	fmt.Println("Accept header -> gin.NegotiateFormat | RFC 9110")
	for _, accept := range []string{
		"",
		"text/csv",
		"application/json;q=0.1, text/csv",
		"text/csv;q=0, */*",
		"Application/JSON",
		"image/png",
		"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
	} {
		fmt.Printf("%q -> %s | %s\n", accept, ginChoice(accept), cmp.Or(negotiate(accept, offers), "(none)"))
	}

	fmt.Println("responses:")
	for _, tc := range []struct{ path, accept string }{
		{"/reports/sales", "application/json"},
		{"/reports/sales", "text/csv"},
		{"/reports/sales", "text/html"},
		{"/reports/sales", "image/png"},
		{"/reports/sales?format=csv", "application/json"},
		{"/reports/sales?format=xml", ""},
		{"/gin-negotiate", "text/csv"},
	} {
		req := httptest.NewRequest(http.MethodGet, tc.path, nil)
		req.Header.Set("Accept", tc.accept)
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		mediaType, _, _ := strings.Cut(w.Header().Get("Content-Type"), ";")
		fmt.Printf("%s Accept=%q -> %d %s vary=%s %s\n", tc.path, tc.accept, w.Code, cmp.Or(mediaType, "-"),
			cmp.Or(w.Header().Get("Vary"), "-"), cmp.Or(strings.ReplaceAll(w.Body.String(), "\n", `\n`), "(no body)"))
	}
}
Read the code

ginChoice builds a fresh test context per header because NegotiateFormat caches the parsed list in c.Accepted. The table shows the three divergences described above; the browser header agrees in both because text/html comes first and has the highest q. In report, a format query parameter is checked against an allow-list and, when present, replaces negotiation entirely, so no Vary is sent. Without it the handler sets Vary: Accept before choosing, so even the 406 carries it. CSV is rendered with encoding/csv into a buffer and sent with c.Data; HTML uses the template installed with SetHTMLTemplate. image/png gets a 406 whose JSON body lists the available types. ?format=xml is a 400, because the URL itself is wrong. The last line is c.Negotiate offered text/csv and asked for text/csv: 406 with no body and no Content-Type, since it has no CSV renderer.

03

406, defaults and Vary: Accept

An empty result means none of your representations is acceptable. Answer 406 Not Acceptable with a body listing what is available, as RFC 9110 suggests, written in your normal error format; a client that accepts only image/png will receive something it did not ask for either way. RFC 9110 also allows ignoring Accept and sending a default instead. Choose one behavior and document it, though for API clients 406 is kinder, because silent JSON delivered to a CSV importer fails later and more confusingly. A missing Accept means anything is acceptable, so put the safest default first in the offers. Browsers send text/html first with /;q=0.8, so a person opening the URL gets HTML. Send Vary: Accept on every negotiated response so caches know the URL has several representations; without it, a CDN that stored the CSV serves it to the next JSON client. The price is fragmentation: every distinct Accept string becomes its own cache key, and many caches do not normalize it. Each representation also needs its own ETag, as the conditional-requests lesson requires.

04

When ?format= beats the Accept header

Negotiation hides the representation in a header, and sometimes it belongs in the URL. A "Download CSV" link in a page or an email cannot set Accept, and a browser's address bar always sends its own. A CDN keys on the URL without needing Vary, and logs and support tickets show exactly what was requested. So many APIs accept ?format=csv, or a suffix such as /sales.csv, as an explicit override validated against an allow-list, and fall back to Accept only when it is absent. An unknown value is a 400 because the URL is wrong; 406 is about the Accept header. Never copy the query value into Content-Type, or ?format=text/html turns your JSON into a page a browser renders, which is reflected XSS. CSV has a hazard of its own: a cell beginning with =, +, - or @ is evaluated as a formula when a user opens the export in a spreadsheet, so prefix such values with a single quote when people will open the file, as OWASP's CSV injection page describes.

05

Test every Accept header you claim to support

Turn the comparison table into a test against your real router. Include a missing header, curl's /, a browser's full header, q=0 exclusions, a low q listed first, letter-case variants and a type you do not offer. Assert the status, the media type parsed from Content-Type and Vary: Accept, and decode each body with the matching reader, encoding/json for JSON and encoding/csv for CSV, so a renderer that writes the wrong format with the right header cannot pass. Add cases for ?format=: a valid override with no Vary, and 400 for an unknown value.

go
func TestReportNegotiation(t *testing.T) {
	gin.SetMode(gin.TestMode)
	r := newRouter()
	cases := []struct {
		accept, wantType string
		wantStatus       int
	}{
		{"", "application/json", 200},
		{"*/*", "application/json", 200},
		{"text/csv", "text/csv", 200},
		{"application/json;q=0.1, text/csv", "text/csv", 200},
		{"text/csv;q=0, */*", "application/json", 200},
		{"TEXT/HTML", "text/html", 200},
		{"text/html,application/xhtml+xml,*/*;q=0.8", "text/html", 200},
		{"image/png", "application/json", 406},
	}
	for _, tc := range cases {
		req := httptest.NewRequest(http.MethodGet, "/reports/sales", nil)
		req.Header.Set("Accept", tc.accept)
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		mt, _, _ := mime.ParseMediaType(w.Header().Get("Content-Type"))
		if w.Code != tc.wantStatus || mt != tc.wantType || w.Header().Get("Vary") != "Accept" {
			t.Errorf("Accept %q: got %d %s, Vary %q", tc.accept, w.Code, mt, w.Header().Get("Vary"))
		}
	}
}
Read the code

This test fragment lives in your service package and runs with go test in your own project; newRouter is the constructor from the first lesson's pattern. Each row names an Accept header and the status and media type you promise for it. mime.ParseMediaType strips the charset parameter so the comparison is about the type alone. The q-value rows and the TEXT/HTML row fail with Gin's NegotiateFormat and pass with the q-aware negotiate function, which is exactly the regression this test exists to catch.

TAKE THIS WITH YOU

Treat Gin's NegotiateFormat as a first-match helper that ignores q-values and letter case, negotiate by q yourself when clients depend on it, answer 406 in your own format, send Vary: Accept on every negotiated response and offer ?format= where URLs must name the representation.

Check your understanding

A client sends Accept: text/csv;q=0, */* and a Gin v1.12.0 handler calls c.NegotiateFormat("application/json", "text/csv"). What does it return?

Go to the source

Progress stays in this browser. No account needed.