github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/httpp/nocache.go (about) 1 package httpp 2 3 import ( 4 "net/http" 5 "time" 6 ) 7 8 var epoch = time.Unix(0, 0).Format(time.RFC1123) 9 10 var noCacheHeaders = map[string]string{ 11 "Expires": epoch, 12 "Cache-Control": "no-cache, private, max-age=0", 13 "Pragma": "no-cache", 14 "X-Accel-Expires": "0", 15 } 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 26 // NoCache set no cache headers for http response. 27 // copy from https://stackoverflow.com/questions/33880343/go-webserver-dont-cache-files-using-timestamp 28 func NoCache(h http.Handler) http.Handler { 29 fn := func(w http.ResponseWriter, r *http.Request) { 30 NoCacheHeaders(w, r) 31 32 h.ServeHTTP(w, r) 33 } 34 35 return http.HandlerFunc(fn) 36 } 37 38 func NoCacheHeaders(w http.ResponseWriter, r *http.Request) { 39 // Delete any ETag headers that may have been set 40 for _, v := range etagHeaders { 41 if r.Header.Get(v) != "" { 42 r.Header.Del(v) 43 } 44 } 45 46 // Set our NoCache headers 47 for k, v := range noCacheHeaders { 48 w.Header().Set(k, v) 49 } 50 }