nocache.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. // Ported from Goji's middleware, source:
  3. // https://github.com/zenazn/goji/tree/master/web/middleware
  4. import (
  5. "net/http"
  6. "time"
  7. )
  8. // Unix epoch time
  9. var epoch = time.Unix(0, 0).UTC().Format(http.TimeFormat)
  10. // Taken from https://github.com/mytrile/nocache
  11. var noCacheHeaders = map[string]string{
  12. "Expires": epoch,
  13. "Cache-Control": "no-cache, no-store, no-transform, must-revalidate, private, max-age=0",
  14. "Pragma": "no-cache",
  15. "X-Accel-Expires": "0",
  16. }
  17. var etagHeaders = []string{
  18. "ETag",
  19. "If-Modified-Since",
  20. "If-Match",
  21. "If-None-Match",
  22. "If-Range",
  23. "If-Unmodified-Since",
  24. }
  25. // NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent
  26. // a router (or subrouter) from being cached by an upstream proxy and/or client.
  27. //
  28. // As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
  29. //
  30. // Expires: Thu, 01 Jan 1970 00:00:00 UTC
  31. // Cache-Control: no-cache, private, max-age=0
  32. // X-Accel-Expires: 0
  33. // Pragma: no-cache (for HTTP/1.0 proxies/clients)
  34. func NoCache(h http.Handler) http.Handler {
  35. fn := func(w http.ResponseWriter, r *http.Request) {
  36. // Delete any ETag headers that may have been set
  37. for _, v := range etagHeaders {
  38. if r.Header.Get(v) != "" {
  39. r.Header.Del(v)
  40. }
  41. }
  42. // Set our NoCache headers
  43. for k, v := range noCacheHeaders {
  44. w.Header().Set(k, v)
  45. }
  46. h.ServeHTTP(w, r)
  47. }
  48. return http.HandlerFunc(fn)
  49. }