Skip to content

Instantly share code, notes, and snippets.

@jlpellicer
Created November 15, 2017 18:10
Show Gist options
  • Save jlpellicer/a1409e90af046ac1fca022e027fa6ab1 to your computer and use it in GitHub Desktop.
Save jlpellicer/a1409e90af046ac1fca022e027fa6ab1 to your computer and use it in GitHub Desktop.
Security headers (Go)
package middleware
import "net/http"
const (
xFrameOptions = "X-Frame-Options"
xFrameOptionsValue = "DENY"
xContentTypeOptions = "X-Content-Type-Options"
xContentTypeOptionsValue = "nosniff"
xssProtection = "X-XSS-Protection"
xssProtectionValue = "1; mode=block"
strictTransportSecurity = "Strict-Transport-Security" // details https://blog.bracelab.com/achieving-perfect-ssl-labs-score-with-go + https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
strictTransportSecurityValue = "max-age=31536000; includeSubDomains; preload" // 31536000 = just shy of 12 months
// also look at Content-Security-Policy in the future.
)
// Security Adds HTTP headers for XSS Protection and alike.
func Security(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(xFrameOptions, xFrameOptionsValue)
w.Header().Add(xContentTypeOptions, xContentTypeOptionsValue)
w.Header().Add(xssProtection, xssProtectionValue)
w.Header().Add(strictTransportSecurity, strictTransportSecurityValue)
next(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment