From 2a87964a794b050599b5352110d858b80eacecc4 Mon Sep 17 00:00:00 2001 From: "kali kaneko (leap communications)" Date: Sat, 11 Apr 2020 23:08:10 +0200 Subject: [feat] nocache --- main.go | 2 +- nocache.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 nocache.go diff --git a/main.go b/main.go index aa57c86..e883834 100644 --- a/main.go +++ b/main.go @@ -254,7 +254,7 @@ func main() { bonafide.listGateways() mux := http.NewServeMux() - jh := &jsonHandler{&geoipdb} + jh := noCache(&jsonHandler{&geoipdb}) mux.Handle("/json", jh) th := &txtHandler{&geoipdb} diff --git a/nocache.go b/nocache.go new file mode 100644 index 0000000..cad8393 --- /dev/null +++ b/nocache.go @@ -0,0 +1,58 @@ +package main + +// Ported from Goji's middleware, source: +// https://github.com/zenazn/goji/tree/master/web/middleware + +import ( + "net/http" + "time" +) + +// 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, no-store, no-transform, must-revalidate, 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) +} -- cgit v1.2.3