Gin in the wider system · 6 MIN READ

Gzip in Gin by hand: negotiate q-values, wrap the writer, add Vary and know what never to compress

Write a gzip middleware for Gin that negotiates Accept-Encoding correctly and skips responses that must not be compressed, and accept gzip request bodies without a decompression-bomb hole.

JSON, CSV and HTML often shrink several times under gzip, which matters on mobile links and metered egress. A compression middleware sits between every handler and the network, so its bugs appear everywhere at once: a missing Vary header serves gzip to a client that cannot read it, a stale Content-Length truncates bodies, a compressed event stream stalls, and a page that mixes a secret with reflected input becomes a BREACH oracle.

gin · A MAP OF THE IDEA

  1. Parse Accept-Encoding
  2. Buffer the first bytes
  3. Decide per response
  4. Fix headers, compress

Useful when

  • Text APIs typically shrink several times on slow links.
  • A per-route opt-out keeps BREACH-prone pages uncompressed.

Watch out

  • Never compress SSE, ranges, images or already-encoded bodies.
  • Bound decompressed request bodies, not just the wire bytes.
  • A reverse proxy or CDN usually compresses better than the app.

Implementation & operation cost: CPU on every compressible response, a small buffer per request, and a wrapper whose every write path must stay in sync with gin.ResponseWriter as Gin evolves.

01

Negotiate with q-values, then decide per response

Accept-Encoding is a list of content codings with optional weights. "gzip, br" accepts both; "gzip;q=0, br" explicitly refuses gzip; "*;q=0.5" accepts any coding not listed. An explicit entry beats the wildcard, q=0 means not acceptable, and several Accept-Encoding header lines form one list, which is why the code joins Header.Values. RFC 9110 lets a server pick any coding when the header is absent, but clients that omit it are usually simple tools, so identity is the safe answer. The client's preference is only half the decision. The other half depends on the response: its status, its Content-Type, its size, whether a Content-Encoding is already set and whether the handler streams. None of that is known before the handler writes, so the wrapper buffers the first bytes and decides at the last possible moment.

02

A gzip writer around gin.ResponseWriter

Compress swaps c.Writer for a gzipWriter that embeds the original gin.ResponseWriter. decide runs exactly once: when buffered bytes reach 512, on Flush or WriteHeaderNow, or after the chain returns. NoCompression lets one handler opt out, and GunzipBody accepts compressed uploads. main sends twelve requests and decodes every gzip response, so a corrupt stream would show up as an error line.

go
package main

import (
	"bytes"
	"compress/gzip"
	"errors"
	"fmt"
	"html"
	"io"
	"mime"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"sync"

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

const minSize = 512 // below this, gzip framing and CPU cost more than they save

// acceptsGzip applies q-values: an explicit gzip entry beats *, and q=0
// means "not acceptable". Several Accept-Encoding lines form one list.
func acceptsGzip(values []string) bool {
	gzipQ, anyQ := -1.0, -1.0
	for part := range strings.SplitSeq(strings.Join(values, ","), ",") {
		coding, params, _ := strings.Cut(part, ";")
		q := 1.0
		for p := range strings.SplitSeq(params, ";") {
			if v, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(p)), "q="); ok {
				if f, err := strconv.ParseFloat(v, 64); err == nil && f >= 0 && f <= 1 {
					q = f
				} else {
					q = 0
				}
			}
		}
		switch strings.ToLower(strings.TrimSpace(coding)) {
		case "gzip", "x-gzip":
			gzipQ = q
		case "*":
			anyQ = q
		}
	}
	if gzipQ >= 0 {
		return gzipQ > 0
	}
	return anyQ > 0
}

// compressible is an allow-list: images, archives, video and fonts are
// already compressed, and an event stream must leave event by event.
func compressible(contentType string) bool {
	mt, _, err := mime.ParseMediaType(contentType)
	if err != nil || mt == "text/event-stream" {
		return false
	}
	return strings.HasPrefix(mt, "text/") || mt == "application/json" || mt == "application/javascript" ||
		mt == "image/svg+xml" || strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml")
}

func addVary(h http.Header, field string) {
	for _, v := range h.Values("Vary") {
		for f := range strings.SplitSeq(v, ",") {
			if strings.EqualFold(strings.TrimSpace(f), field) {
				return
			}
		}
	}
	h.Add("Vary", field)
}

var gzPool = sync.Pool{New: func() any { return gzip.NewWriter(io.Discard) }}

// gzipWriter buffers the first bytes so the decision can see the status,
// the headers and whether the body is big enough to be worth compressing.
type gzipWriter struct {
	gin.ResponseWriter
	accepts  bool
	disabled bool
	decided  bool
	buf      []byte
	gz       *gzip.Writer
}

func (w *gzipWriter) decide(sizeKnown bool) {
	if w.decided {
		return
	}
	w.decided = true
	h, status := w.Header(), w.Status()
	if status == http.StatusNotModified {
		addVary(h, "Accept-Encoding") // a 304 repeats the Vary of the 200 it stands for
		return
	}
	if w.disabled || status < 200 || status == http.StatusNoContent || status == http.StatusPartialContent ||
		h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) {
		return
	}
	addVary(h, "Accept-Encoding") // caches must key this URL by Accept-Encoding
	if !w.accepts || (sizeKnown && len(w.buf) < minSize) {
		return
	}
	h.Set("Content-Encoding", "gzip")
	h.Del("Content-Length") // it described the uncompressed bytes
	h.Del("Accept-Ranges")  // ranges would now address the compressed stream
	if etag := h.Get("ETag"); strings.HasPrefix(etag, `"`) {
		h.Set("ETag", "W/"+etag) // different bytes, so no longer a strong validator
	}
	w.gz = gzPool.Get().(*gzip.Writer)
	w.gz.Reset(w.ResponseWriter)
}

func (w *gzipWriter) flushBuf() error {
	buf := w.buf
	w.buf = nil
	if len(buf) == 0 {
		return nil
	}
	if w.gz != nil {
		_, err := w.gz.Write(buf)
		return err
	}
	_, err := w.ResponseWriter.Write(buf)
	return err
}

func (w *gzipWriter) Write(p []byte) (int, error) {
	if !w.decided {
		w.buf = append(w.buf, p...)
		if len(w.buf) < minSize {
			return len(p), nil
		}
		w.decide(false)
		return len(p), w.flushBuf()
	}
	if w.gz != nil {
		return w.gz.Write(p)
	}
	return w.ResponseWriter.Write(p)
}

// Every write path must go through the wrapper, or bytes bypass gzip.
func (w *gzipWriter) WriteString(s string) (int, error) { return w.Write([]byte(s)) }

func (w *gzipWriter) Written() bool { return len(w.buf) > 0 || w.ResponseWriter.Written() }

func (w *gzipWriter) WriteHeaderNow() {
	w.decide(false)
	w.flushBuf()
	w.ResponseWriter.WriteHeaderNow()
}

func (w *gzipWriter) Flush() {
	w.decide(false)
	w.flushBuf()
	if w.gz != nil {
		w.gz.Flush()
	}
	w.ResponseWriter.Flush()
}

func (w *gzipWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }

func (w *gzipWriter) finish() {
	w.decide(true)
	w.flushBuf()
	if w.gz != nil {
		w.gz.Close() // writes the gzip trailer
		gzPool.Put(w.gz)
		w.gz = nil
	}
}

func Compress() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == http.MethodHead {
			c.Next() // no body to compress
			return
		}
		w := &gzipWriter{ResponseWriter: c.Writer, accepts: acceptsGzip(c.Request.Header.Values("Accept-Encoding"))}
		c.Writer = w
		c.Next()
		w.finish()
		c.Writer = w.ResponseWriter
	}
}

// NoCompression opts one response out: use it for pages that mix a secret
// with reflected input, the precondition for BREACH.
func NoCompression(c *gin.Context) {
	if w, ok := c.Writer.(*gzipWriter); ok {
		w.disabled = true
	}
}

// GunzipBody accepts gzip request bodies and bounds the compressed and
// the decompressed size separately.
func GunzipBody(maxWire, maxDecoded int64) gin.HandlerFunc {
	return func(c *gin.Context) {
		switch strings.ToLower(c.GetHeader("Content-Encoding")) {
		case "":
			c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxDecoded)
			c.Next()
			return
		case "gzip":
		default:
			c.Header("Accept-Encoding", "gzip") // RFC 7694: say what would work
			c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{"error": "unsupported_content_encoding"})
			return
		}
		zr, err := gzip.NewReader(http.MaxBytesReader(c.Writer, c.Request.Body, maxWire))
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid_gzip"})
			return
		}
		c.Request.Body = http.MaxBytesReader(c.Writer, zr, maxDecoded)
		c.Request.Header.Del("Content-Encoding")
		c.Request.ContentLength = -1
		c.Next()
	}
}

func gzipped(b []byte) []byte {
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	zw.Write(b)
	zw.Close()
	return buf.Bytes()
}

func main() {
	gin.SetMode(gin.TestMode)
	report := []byte("region,orders,total\n" + strings.Repeat("eu-west,1200,98000.00\n", 180))
	r := gin.New()
	r.Use(Compress())
	r.GET("/report", func(c *gin.Context) {
		c.Header("ETag", `"r1"`)
		if strings.TrimPrefix(c.GetHeader("If-None-Match"), "W/") == `"r1"` {
			c.Status(http.StatusNotModified)
			return
		}
		c.Data(http.StatusOK, "text/csv; charset=utf-8", report)
	})
	r.GET("/small", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
	r.GET("/logo.png", func(c *gin.Context) { c.Data(http.StatusOK, "image/png", make([]byte, 2048)) })
	r.GET("/events", func(c *gin.Context) {
		c.Header("Content-Type", "text/event-stream")
		for i := 1; i <= 3; i++ {
			fmt.Fprintf(c.Writer, "data: tick %d\n\n", i)
			c.Writer.Flush()
		}
	})
	r.GET("/account", func(c *gin.Context) {
		NoCompression(c) // the CSRF token and the reflected query share one body
		page := `<form><input type="hidden" name="csrf" value="tok-test-9f2c">` +
			"<p>Results for " + html.EscapeString(c.Query("q")) + "</p>" + strings.Repeat("<li>row</li>", 60) + "</form>"
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(page))
	})
	r.POST("/import", GunzipBody(64<<10, 1<<20), func(c *gin.Context) {
		data, err := io.ReadAll(c.Request.Body)
		var tooBig *http.MaxBytesError
		switch {
		case errors.As(err, &tooBig):
			c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "body_too_large", "limit": tooBig.Limit})
		case err != nil:
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body"})
		default:
			c.JSON(http.StatusOK, gin.H{"imported": len(data)})
		}
	})

	show := func(label string, req *http.Request) {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		body := w.Body.Bytes()
		enc := w.Header().Get("Content-Encoding")
		if enc == "gzip" {
			zr, err := gzip.NewReader(bytes.NewReader(body))
			if err == nil {
				body, err = io.ReadAll(zr)
			}
			if err != nil {
				fmt.Println(label, "corrupt gzip:", err)
				return
			}
		}
		line := fmt.Sprintf("%-14s %d enc=%s vary=%s", label, w.Code, cmpOr(enc, "-"), cmpOr(w.Header().Get("Vary"), "-"))
		if etag := w.Header().Get("ETag"); etag != "" {
			line += " etag=" + etag
		}
		if strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") {
			line += " " + string(body)
		} else {
			line += " body=" + strconv.Itoa(len(body))
		}
		if enc == "gzip" {
			line += " smaller=" + strconv.FormatBool(w.Body.Len() < len(body))
		}
		fmt.Println(line)
	}
	get := func(path, acceptEncoding string, kv ...string) *http.Request {
		req := httptest.NewRequest(http.MethodGet, path, nil)
		if acceptEncoding != "" {
			req.Header.Set("Accept-Encoding", acceptEncoding)
		}
		for i := 0; i+1 < len(kv); i += 2 {
			req.Header.Set(kv[i], kv[i+1])
		}
		return req
	}
	upload := func(encoding string, body []byte) *http.Request {
		req := httptest.NewRequest(http.MethodPost, "/import", bytes.NewReader(body))
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Content-Encoding", encoding)
		return req
	}

	show("gzip", get("/report", "gzip, deflate, br"))
	show("gzip;q=0", get("/report", "gzip;q=0, br"))
	show("*;q=0.5", get("/report", "*;q=0.5"))
	show("no header", get("/report", ""))
	show("revalidate", get("/report", "gzip", "If-None-Match", `W/"r1"`))
	show("small json", get("/small", "gzip"))
	show("png", get("/logo.png", "gzip"))
	show("sse", get("/events", "gzip"))
	show("breach opt-out", get("/account?q=reflected", "gzip"))
	rows := []byte(`[` + strings.Repeat(`{"sku":"A-1","qty":3},`, 99) + `{"sku":"A-1","qty":3}]`)
	show("upload gzip", upload("gzip", gzipped(rows)))
	bomb := gzipped(make([]byte, 8<<20))
	fmt.Println("bomb: 8 MiB of zeros, gzip under 64 KiB:", len(bomb) < 64<<10)
	show("upload bomb", upload("gzip", bomb))
	show("upload br", upload("br", []byte("x")))
}

func cmpOr(s, fallback string) string {
	if s == "" {
		return fallback
	}
	return s
}
Read the code

Overriding Write is not enough. gin.ResponseWriter also has WriteString, which io.WriteString and Gin's renderers can reach, and an embedded method would send bytes straight past gzip; WriteHeaderNow is what c.Render calls for 204 and 304 and what AbortWithStatus calls. Status works through the embedded writer because Gin's WriteHeader only records the code until the first real write. finish runs after c.Next and before Gin's engine flushes its own writer, and gz.Close writes the gzip trailer. Unwrap lets http.ResponseController reach SetWriteDeadline, while its Flush finds the wrapper's Flush first, because ResponseController checks for a Flusher before unwrapping. Writers come from a sync.Pool because each gzip.Writer carries sizeable compressor state. In the output, gzip;q=0 and the missing header get identity, *;q=0.5 gets gzip, the 304 carries Vary and no body, and the PNG, the event stream and the opted-out page pass through untouched.

03

Headers that must change with the body

Add Vary: Accept-Encoding to every response whose encoding depends on that header, including the identity ones; otherwise a shared cache that stored the gzip variant serves it to a client that sent no Accept-Encoding. A 304 must repeat the Vary its 200 would carry. Delete Content-Length, which described the uncompressed bytes. A strong ETag names exact bytes, as the conditional-requests lesson explains, so weaken it as nginx does or compute one per coding; the handler's If-None-Match check uses the weak comparison, so W/"r1" still revalidates. Drop Accept-Ranges, because ranges would address the compressed stream. Skip HEAD, which has no body; 1xx, 204 and 304; 206 partial content; bodies that already have a Content-Encoding, such as precompressed assets; and every type outside the allow-list. PNG, JPEG, ZIP, video and WOFF2 are already compressed, so gzip burns CPU and can even grow them. Never compress text/event-stream: the compressor holds bytes until a block fills and proxies may buffer further, which delays the events and heartbeats the SSE lesson relies on. Below roughly half a kilobyte, gzip framing and CPU cost more than they save.

04

Decompression bombs: bound the bytes after gunzip

DEFLATE can shrink a run of zeros by about a thousand to one: the program's 8 MiB of zeros fits in well under 64 KiB of gzip. A limit on Content-Length or on wire bytes therefore says nothing about memory. GunzipBody applies http.MaxBytesReader twice, once to the compressed stream and once to the decompressed stream; it can wrap the *gzip.Reader because that type has a Close method. When the decoded limit trips, the handler sees *http.MaxBytesError and answers 413. One v1.12.0 surprise: MaxBytesReader asks net/http to close the connection through an unexported method that only the server's own ResponseWriter has, and Gin's writer does not forward it, so passing c.Writer loses that signal; the server still discards at most 256 KiB of unread body after the handler and closes the connection when more remains. The middleware removes Content-Encoding and sets ContentLength to -1, so later binding code does not trust values that described the compressed bytes. A coding you do not support gets 415 with an Accept-Encoding response header naming what does work, as RFC 7694 describes. gzip.Reader reads concatenated members as one stream by default, and the decoded limit still holds across them. Apply the same rule wherever you decompress yourself: upstream responses when you set Accept-Encoding manually, and archives, whose zip-slip half the path-traversal lesson covers.

05

BREACH, and when the proxy should compress instead

BREACH needs four things: HTTP compression, a secret such as a CSRF token in the body, attacker-controlled input reflected into the same body, and an attacker who can make the victim's browser send many requests and observe the encrypted response sizes. Guesses that match the secret compress better, so the response gets shorter, and the secret is recovered byte by byte despite TLS. Defenses: turn compression off for such pages, as NoCompression does for the account page; mask the token with a fresh random pad per response so its bytes never repeat; keep secrets out of bodies that echo input; and limit cross-site request driving with SameSite cookies and the Sec-Fetch-Site checks from the CSRF lesson. When nginx, Envoy, a load balancer or a CDN sits in front of the service, let it compress: it offers brotli and zstd, caches compressed variants and keeps the CPU off your application. Compress in the app only when nothing in front can, and never in both places.

text
# nginx in front of the Gin service: compress here, not in the app
gzip            on;
gzip_min_length 1024;
gzip_proxied    any;
gzip_vary       on;
gzip_types      application/json text/csv image/svg+xml;

location /events {
    proxy_pass       http://app;
    proxy_buffering  off;   # SSE must reach the client event by event
    gzip             off;
}
Read the code

This nginx configuration is an illustration for your own deployment, not part of the Go program. gzip_vary on adds Vary: Accept-Encoding, gzip_proxied any keeps compressing when the request itself arrived through another proxy such as a CDN, which nginx detects from the Via header, and gzip_types is an allow-list just like compressible. The /events location turns off both proxy buffering and gzip, so Server-Sent Events leave the proxy as soon as the Gin handler flushes them. With this in place, remove Compress from the Gin engine rather than running both.

TAKE THIS WITH YOU

Compress only allow-listed, non-streaming bodies big enough to benefit, add Vary: Accept-Encoding and drop Content-Length when you do, bound gzip request bodies after decompression, and switch compression off for pages that mix secrets with reflected input.

Check your understanding

A gzip middleware compresses responses for clients that send Accept-Encoding: gzip. Which header stops a shared cache from serving the compressed bytes to a client that cannot decode them?

Go to the source

Progress stays in this browser. No account needed.