Gin in production · 6 MIN READ

Conditional GETs in Gin: strong ETags from response bytes, 304 Not Modified and safe Cache-Control

Serve ETag and Last-Modified validators, answer conditional requests with 304, and choose Cache-Control so private data never lands in a shared cache.

A conditional GET lets a client that already holds a copy ask whether it is still current. When it is, the server answers 304 Not Modified with no body, which saves bandwidth and the client's parsing time. The mechanism has three parts: a validator on every response, a comparison on every request, and a Cache-Control policy that decides who may keep a copy. The policy is where private data leaks.

gin · A MAP OF THE IDEA

  1. Render bytes once
  2. Hash to strong ETag
  3. INM before IMS
  4. 304 or 200 + policy

Useful when

  • Unchanged responses cost a header round trip, not a body.
  • Byte-derived ETags are always correct, even for same-second edits.

Watch out

  • public on per-user data lets shared caches leak it.
  • Hashing still renders the full response; it saves bandwidth, not work.

Implementation & operation cost: A SHA-256 over each response body and a few header checks; version-based validators save more but need a reliable version source.

01

Validators and the order RFC 9110 prescribes

An ETag is an opaque, quoted identifier for one representation of a resource. A strong ETag such as "a1fe" promises byte-for-byte identity, while a weak one such as W/"a1fe" promises only semantic equivalence. Last-Modified is a date with one-second resolution. Clients send them back as If-None-Match and If-Modified-Since. The order matters: when If-None-Match is present, the server evaluates it and ignores If-Modified-Since, and the date is consulted only when no ETag condition was sent. If-None-Match uses the weak comparison, so W/"x" matches "x". A 304 must carry the ETag, Cache-Control, Vary and Expires headers that a 200 would have carried, so a cache can refresh the metadata of its stored copy. This handling applies to GET and HEAD. For state-changing methods, a failed If-None-Match means 412 Precondition Failed, and If-Match is the tool for optimistic concurrency on updates.

02

Hash the bytes, compare, then send 200 or 304

serve renders the value to bytes once, derives a strong ETag from the SHA-256 of those bytes, and sets the validators and caching headers before it decides between a bodiless 304 and a 200 carrying the bytes. The requests cover a first fetch, revalidation by ETag in strong and weak form, revalidation by date, an edit made 400 ms after the previous one, and a private endpoint.

go
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

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

type Article struct {
	ID      int       `json:"id"`
	Title   string    `json:"title"`
	Updated time.Time `json:"updated"`
}

// strongETag names these exact bytes: any change in the body changes it.
func strongETag(body []byte) string {
	sum := sha256.Sum256(body)
	return `"` + hex.EncodeToString(sum[:12]) + `"`
}

// matches applies the weak comparison RFC 9110 requires for If-None-Match.
func matches(ifNoneMatch, etag string) bool {
	if strings.TrimSpace(ifNoneMatch) == "*" {
		return true
	}
	for candidate := range strings.SplitSeq(ifNoneMatch, ",") {
		if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == etag {
			return true
		}
	}
	return false
}

func notModified(c *gin.Context, etag string, modified time.Time) bool {
	if inm := c.GetHeader("If-None-Match"); inm != "" {
		return matches(inm, etag) // when present, If-Modified-Since is ignored
	}
	since, err := http.ParseTime(c.GetHeader("If-Modified-Since"))
	return err == nil && !modified.Truncate(time.Second).After(since)
}

// serve renders v once, then answers 200 with the bytes or 304 without them.
func serve(c *gin.Context, cacheControl string, modified time.Time, v any) {
	body, err := json.Marshal(v)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	etag := strongETag(body)
	c.Header("ETag", etag)
	c.Header("Cache-Control", cacheControl)
	if !modified.IsZero() {
		c.Header("Last-Modified", modified.UTC().Format(http.TimeFormat))
	}
	if notModified(c, etag, modified) {
		c.Status(http.StatusNotModified) // same validators and caching headers, no body
		return
	}
	c.Data(http.StatusOK, "application/json; charset=utf-8", body)
}

func main() {
	gin.SetMode(gin.TestMode)
	article := Article{ID: 7, Title: "Draining HTTP servers", Updated: time.Date(2026, 11, 2, 9, 30, 0, 0, time.UTC)}

	r := gin.New()
	r.GET("/articles/:id", func(c *gin.Context) {
		serve(c, "public, max-age=60", article.Updated, article)
	})
	r.GET("/me", func(c *gin.Context) {
		if c.GetHeader("Authorization") != "Bearer t-user-17" {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		c.Header("Vary", "Authorization")
		serve(c, "private, no-cache", time.Time{}, gin.H{"user": "user-17", "plan": "team"})
	})

	get := func(label, path string, headers ...string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("GET", path, nil)
		for i := 0; i+1 < len(headers); i += 2 {
			req.Header.Set(headers[i], headers[i+1])
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Printf("%s: %d etag=%s cache=%q bytes=%d\n", label, w.Code,
			w.Header().Get("ETag"), w.Header().Get("Cache-Control"), w.Body.Len())
		return w
	}

	first := get("first fetch", "/articles/7")
	etag, lastModified := first.Header().Get("ETag"), first.Header().Get("Last-Modified")
	fmt.Println("  Last-Modified:", lastModified)
	get("If-None-Match", "/articles/7", "If-None-Match", etag)
	get("weak If-None-Match", "/articles/7", "If-None-Match", "W/"+etag)
	get("If-Modified-Since", "/articles/7", "If-Modified-Since", lastModified)

	// An edit 400ms later: same second, so Last-Modified cannot see it.
	article.Title = "Draining HTTP servers safely"
	article.Updated = article.Updated.Add(400 * time.Millisecond)
	get("edited, If-Modified-Since", "/articles/7", "If-Modified-Since", lastModified)
	get("edited, If-None-Match", "/articles/7", "If-None-Match", etag)
	get("private data", "/me", "Authorization", "Bearer t-user-17")
}
Read the code

strongETag quotes the first 12 bytes of the SHA-256 digest in hex; 96 bits makes an accidental collision between versions of one resource irrelevant. Because the ETag names the exact bytes, any change to the JSON changes it. matches splits the header's list, strips W/ to perform the weak comparison and accepts *. notModified checks If-None-Match first and looks at If-Modified-Since only when it is absent, truncating the modification time to whole seconds as the header format does. The edited article shows why the order matters. The edit happened within the same second, so the date check wrongly answers 304. Worse, that 304 carries the new ETag, so a cache would pair the old body with the new validator and keep revalidating it successfully. The ETag check returns the new 82 bytes. c.Status(304) leaves the body empty, and Gin writes the header when the chain ends.

03

Cache-Control for public and private data

Validators say whether a copy is current; Cache-Control says who may keep one and for how long. public, max-age=60 lets any cache, including CDNs and shared proxies, serve the response for 60 seconds without asking and then revalidate with the ETag, which suits data that is identical for every caller. private, no-cache lets only the user's own browser store the response and requires revalidation before each use, which suits per-user data where a 304 still saves the body. no-store forbids keeping a copy at all, which suits tokens, payment details and anything you would not want in a shared computer's disk cache. Note that no-cache does not mean do not cache; it means do not reuse without revalidating. Under RFC 9111, a shared cache must not reuse a response to a request with an Authorization header unless the response explicitly allows it with public, s-maxage or must-revalidate. Adding public to a per-user response therefore removes exactly the protection that kept the CDN from serving it to the next user. HTTP gives cookie-authenticated responses no such default, so mark them private explicitly, and list every request header that changes the response in Vary.

04

Where the ETag should come from

Hashing the rendered bytes is simple and always correct, but the server still loads and renders everything, so a 304 saves bandwidth and client parsing, not database time. When rendering is expensive, derive the validator from a version instead: a row version, or an update timestamp with sub-second precision, combined with whatever shapes the representation, such as API version, language or selected fields. That lets the handler answer 304 before loading the full object. A strong ETag names one representation, including its content coding, so if middleware gzips the body, the compressed bytes need a different strong ETag, or a weak one. Serialization must be deterministic for byte hashing to work. encoding/json sorts map keys, but a hand-written encoder that ranges over a map does not, and every response would then look new. ETags are visible to clients, so never build them from secrets. For files and blobs, http.ServeContent implements If-None-Match, If-Modified-Since and Range for you once you set the ETag header.

05

Test the contract, not just the 200

Assert that the first fetch returns an ETag and the intended Cache-Control. A matching If-None-Match should give 304 with an empty body and the same validators. A weak form, a list of several tags and * should all match, and a different tag should give 200. If-Modified-Since alone should work, If-None-Match should take precedence over it, and a same-second edit should be detected. Private routes must never say public, and routes whose output depends on Authorization must list it in Vary. HEAD should behave like GET without a body. The most valuable test runs in a staging environment behind the real CDN: request a private resource as user A, then as user B, and confirm that B never receives A's body. That single check catches the configuration mistakes that unit tests of the handler cannot see.

TAKE THIS WITH YOU

Compute a strong ETag from the exact response bytes or a precise version, check If-None-Match before If-Modified-Since, answer 304 with the same validators and caching headers but no body, and mark per-user data private or no-store so shared caches never serve it to someone else.

Check your understanding

A per-user /me response is sent with Cache-Control: public, max-age=60 behind a CDN. What can go wrong?

Go to the source

Progress stays in this browser. No account needed.