Set Security Headers In Middleware

Wrap any handler with middleware that injects nosniff, frame-deny, referrer and CSP headers so every response ships the same baseline defenses.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

// securityHeaders middleware:每个响应统一注入安全响应头
func securityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h := w.Header()
		h.Set("X-Content-Type-Options", "nosniff")
		h.Set("X-Frame-Options", "DENY")
		h.Set("Referrer-Policy", "no-referrer")
		h.Set("Content-Security-Policy", "default-src 'self'")
		next.ServeHTTP(w, r)
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	server := httptest.NewServer(securityHeaders(mux))
	defer server.Close()

	resp, err := http.Get(server.URL + "/api/status")
	if err != nil {
		fmt.Println("get:", err)
		return
	}
	resp.Body.Close()
	for _, name := range []string{"X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy", "Content-Security-Policy"} {
		fmt.Println(name+":", resp.Header.Get(name))
	}
}

A closer look

Set Security Headers In Middleware reduces to the functions securityHeaders and main.

One loop does the cycling here: for _, name := range []string{"X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy", "Co…. err is inspected at 1 call site before any result is trusted. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Caveats

  • Fully self-contained: imports, if any, come from the runtime itself.

Using it

Signature: func securityHeaders(next http.Handler) http.Handler

The demo output is labeled (get:); each label names the call that printed it.

Execute the file and main walks through securityHeaders, in that order.

Key statements

for _, name := range []string{"X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy", "Content-Security-Policy"} {
	fmt.Println(name+":", resp.Header.Get(name))
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	h := w.Header()
	h.Set("X-Content-Type-Options", "nosniff")
	h.Set("X-Frame-Options", "DENY")
	h.Set("Referrer-Policy", "no-referrer")
	h.Set("Content-Security-Policy", "default-src 'self'")
	next.ServeHTTP(w, r)
})
if err != nil {
	fmt.Println("get:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Set Security Headers In Middleware print when run?
Invoke the file as-is — the `get:` prefixes identify which step printed each line.