LogoPly
Middleware

Security Headers

Add browser security headers to every response.

Security Headers

middleware.SecurityHeaders sets common browser security headers before the handler runs.

app.Use(middleware.SecurityHeaders())

The defaults set:

HeaderValue
X-Content-Type-Optionsnosniff
X-Frame-OptionsDENY
Referrer-Policystrict-origin-when-cross-origin
Permissions-Policycamera=(), microphone=(), geolocation=()

HSTS is disabled by default. Content Security Policy and Cross-Origin-Opener-Policy are also unset unless you provide them.

Custom options

app.Use(middleware.SecurityHeaders(middleware.SecurityHeadersOptions{
	FrameOptions:            "SAMEORIGIN",
	ContentSecurityPolicy:   "default-src 'self'; img-src 'self' data:",
	CrossOriginOpenerPolicy: "same-origin",
	HSTSMaxAge:              365 * 24 * time.Hour,
	HSTSIncludeSubdomains:   true,
	HSTSPreload:             true,
}))
OptionDescription
ContentSecurityPolicyFull Content-Security-Policy value
FrameOptionsDENY or SAMEORIGIN
ReferrerPolicyReferrer policy value
PermissionsPolicyBrowser feature policy
CrossOriginOpenerPolicysame-origin, same-origin-allow-popups, or unsafe-none
HSTSMaxAgeHSTS lifetime. Zero disables the header
HSTSIncludeSubdomainsAdds includeSubDomains
HSTSPreloadAdds preload

HSTS

Only enable HSTS after the site works over HTTPS. Browsers cache the policy for the configured lifetime, so a mistake can lock users out of the HTTP version.

Start with a short lifetime and no preload during rollout:

HSTSMaxAge: 5 * time.Minute,

Increase the lifetime after the HTTPS setup is stable. The preload directive does not submit the domain to browser preload lists. That requires a separate submission.

Content Security Policy

CSP can break inline scripts, styles, and third-party widgets. Build the policy from the assets the application actually loads, test it in report-only mode at the proxy, then enforce it here.

Ordering

Place security headers before handlers that may write a response:

app.Use(
	middleware.RequestID(),
	middleware.SecurityHeaders(),
	middleware.Logger(),
)