Hardening a small HTTP server
One middleware sets every security header, and the server sets four timeouts. Neither needs a library.
A small site still deserves the boring defences. This server answers GET requests and nothing else, so the work is short: put headers on every response, and make sure a slow client cannot hold a connection open forever.

Headers in one place
The middleware wraps the whole mux, so no handler can forget a header and no handler has to repeat one.
const policy = "default-src 'none'; script-src 'self'; img-src 'self'; " +
"style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", policy)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
next.ServeHTTP(w, r)
})
}
default-src 'none' is the important line. Everything the page needs is then
listed back: one stylesheet, one script, and images from this host. A stray
<script src="https://cdn..."> in a template fails in the browser instead of
silently loading.

Timeouts, not features
The zero value of http.Server has no timeouts, which turns a slow client into
a way to keep file descriptors open. Four numbers fix that:
| Field | Value | What it bounds |
|---|---|---|
ReadHeaderTimeout |
5s | The header block |
ReadTimeout |
10s | The whole request |
WriteTimeout |
15s | The response write |
MaxHeaderBytes |
16 KB | Header size |
ReadHeaderTimeout is the one that matters most in practice, because it is the
cheap defence against a client that opens a connection and sends nothing.
What the policy buys
- No inline script, so a template cannot smuggle behaviour into the page.
- No external origin, so the browser cannot be the exfiltration path.
- No framing, so the site cannot be wrapped in someone else's page.
- No referrer, so an outbound click does not leak the page the reader came from.
A header you set once is worth more than a comment that says you remembered.
What this does not do
There is no rate limit, no bot filter, and no WAF. Those belong to the edge in front of the server, or they need state this process does not keep. Saying that out loud is part of the design: the server does the part it can do correctly and leaves the rest to a layer that is better at it.