Skip to content

Instantly share code, notes, and snippets.

@jubobs
Last active September 7, 2018 17:59
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 jubobs/79e595dba191dab93b1308668b4730bb to your computer and use it in GitHub Desktop.
Save jubobs/79e595dba191dab93b1308668b4730bb to your computer and use it in GitHub Desktop.
A wrapper for HTTP handlers with sensible defaults (objective: get a perfect score on https://observatory.mozilla.org)
package main
import (
"fmt"
"net/http"
"google.golang.org/appengine"
)
func main() {
http.HandleFunc("/", secure(handle))
appengine.Main()
}
func handle(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!")
}
func secure(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("Strict-Transport-Security", "max-age=63072000")
w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.URL.Scheme == "http" {
url := "https://" + r.Host + r.RequestURI
http.Redirect(w, r, url, http.StatusMovedPermanently)
}
handler(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment