Tags: #golang #go #middleware
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
var securityHeaders = map[string]string{
"Referrer-Policy": "Same-origin",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "SAMEORIGIN",
"X-XSS-Protection": "1; mode=block",
}
func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func middleware(handler httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
for key, val := range securityHeaders {
if w.Header().Get(key) == "" {
w.Header().Set(key, val)
}
}
handler(w, r, p)
}
}
func main() {
router := httprouter.New()
router.GET("/", middleware(index))
log.Fatal(http.ListenAndServe(":8080", router))
}
$ curl -v http://localhost:8080/
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
< HTTP/1.1 200 OK
< Referrer-Policy: Same-origin
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-Xss-Protection: 1; mode=block
< Date: Tue, 27 Mar 2018 15:46:42 GMT
< Content-Length: 9
< Content-Type: text/plain; charset=utf-8
Welcome!
* Connection #0 to host localhost left intact