Skip to content

Instantly share code, notes, and snippets.

@graphaelli
Created June 15, 2017 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphaelli/538cbed4bb77973f498a9ba20ac1b149 to your computer and use it in GitHub Desktop.
Save graphaelli/538cbed4bb77973f498a9ba20ac1b149 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
"time"
)
// https://raw.githubusercontent.com/zenazn/goji/master/web/middleware/nocache.go
// Unix epoch time
var epoch = time.Unix(0, 0).Format(time.RFC1123)
// Taken from https://github.com/mytrile/nocache
var noCacheHeaders = map[string]string{
"Expires": epoch,
"Cache-Control": "no-cache, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
var etagHeaders = []string{
"ETag",
"If-Modified-Since",
"If-Match",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
}
// NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent
// a router (or subrouter) from being cached by an upstream proxy and/or client.
//
// As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
// Expires: Thu, 01 Jan 1970 00:00:00 UTC
// Cache-Control: no-cache, private, max-age=0
// X-Accel-Expires: 0
// Pragma: no-cache (for HTTP/1.0 proxies/clients)
func NoCache(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Delete any ETag headers that may have been set
for _, v := range etagHeaders {
if r.Header.Get(v) != "" {
r.Header.Del(v)
}
}
// Set our NoCache headers
for k, v := range noCacheHeaders {
w.Header().Set(k, v)
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func LogHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r)
h.ServeHTTP(w, r)
})
}
func main() {
listen := ":8080"
log.Printf("listening on %s", listen)
log.Fatal(http.ListenAndServe(listen, LogHandler(NoCache(http.FileServer(http.Dir("."))))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment