go 12 lines · 1 tab

ETag handling for conditional GETs (cheap caching)

Leah Thompson Jan 2026
1 tab
package api

import "net/http"

func ETag(w http.ResponseWriter, r *http.Request, etag string) bool {
  w.Header().Set("ETag", etag)
  if inm := r.Header.Get("If-None-Match"); inm != "" && inm == etag {
    w.WriteHeader(http.StatusNotModified)
    return true
  }
  return false
}
1 file · go Explain with highlit

ETags are a low-effort way to cut bandwidth and CPU when clients poll for resources that rarely change. The server computes an ETag for the representation (often a version, content hash, or updated_at value) and compares it to If-None-Match. If they match, we return 304 Not Modified with no body. The detail that matters is consistency: your ETag must change whenever the response body would change, or caches lie. I like using stable version strings (like a row version or sha256) rather than timestamps that can drift. I also set Cache-Control to a short max-age for CDN friendliness. In practice this is a huge win for endpoints like profile pages, settings payloads, and feature-flag documents.


Related snips

Share this code

Here's the card — post it anywhere.

ETag handling for conditional GETs (cheap caching) — share card
Link copied