certViewer/cmd/web/middleware.go (39 lines of code) (raw):

/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package main import ( "fmt" "net/http" ) // secureHeaders follows some security best practices func secureHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' fonts.googleapis.com; font-src fonts.gstatic.com") w.Header().Set("Referrer-Policy", "origin-when-cross-origin") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "deny") w.Header().Set("X-XSS-Protection", "0") next.ServeHTTP(w, r) }) } // logRequest handles logging of requests to server func (app *application) logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var ( ip = r.RemoteAddr proto = r.Proto method = r.Method uri = r.URL.RequestURI() ) app.logger.Info("Received request", "ip", ip, "proto", proto, "method", method, "uri", uri) next.ServeHTTP(w, r) }) } // recoverPanic recovers from server panics and returns an error instead func (app *application) recoverPanic(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { w.Header().Set("Connection", "close") app.serverError(w, r, fmt.Errorf("%s", err)) } }() next.ServeHTTP(w, r) }) }