Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement HTTP response caching in a Go service?
HTTP caching reduces load and improves response times. Go services implement caching at multiple levels: HTTP Cache-Control headers (browser/CDN caching), application-level caching (Redis/in-memory), and conditional requests (ETag/Last-Modified).
// HTTP Cache-Control headers
func publicDataHandler(w http.ResponseWriter, r *http.Request) {
// Cache in browser and CDN for 60s, stale for 10s
w.Header().Set("Cache-Control", "public, max-age=60, stale-while-revalidate=10")
w.Header().Set("Vary", "Accept-Encoding") // vary by encoding
// ... serve data
}
func privateDataHandler(w http.ResponseWriter, r *http.Request) {
// No CDN caching — only browser may cache, private to user
w.Header().Set("Cache-Control", "private, max-age=30")
// ... serve user-specific data
}
// ETag-based conditional caching
func userHandler(w http.ResponseWriter, r *http.Request) {
user, err := svc.GetUser(r.Context(), r.PathValue("id"))
if err != nil { /* handle error */ return }
// Compute ETag (hash of the content)
data, _ := json.Marshal(user)
etag := fmt.Sprintf(`"%x"`, md5.Sum(data))
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "private, must-revalidate")
// Check if client has current version
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified) // 304: send no body
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
// In-memory LRU cache middleware
func cacheMiddleware(cache *lru.Cache, ttl time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet { next.ServeHTTP(w, r); return }
key := r.URL.RequestURI()
if val, ok := cache.Get(key); ok {
w.Header().Set("X-Cache", "HIT")
w.Write(val.([]byte)); return
}
crw := &capturingResponseWriter{ResponseWriter: w}
next.ServeHTTP(crw, r)
cache.Add(key, crw.body)
})
}
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
