Files
rs_website/internal/handler/middleware.go
2026-04-13 03:51:22 -05:00

59 lines
1.8 KiB
Go

package handler
import (
"log"
"net/http"
"strings"
"time"
)
// Chain wraps h with each middleware in order (first applied outermost).
func Chain(h http.Handler, mw ...func(http.Handler) http.Handler) http.Handler {
for i := len(mw) - 1; i >= 0; i-- {
h = mw[i](h)
}
return h
}
// LoggingMiddleware logs method, path, status code, and duration.
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lw := &loggingResponseWriter{ResponseWriter: w, code: http.StatusOK}
next.ServeHTTP(lw, r)
log.Printf("%s %s %d %s", r.Method, r.URL.RequestURI(), lw.code, time.Since(start))
})
}
type loggingResponseWriter struct {
http.ResponseWriter
code int
}
func (lw *loggingResponseWriter) WriteHeader(code int) {
lw.code = code
lw.ResponseWriter.WriteHeader(code)
}
// SecurityHeadersMiddleware sets security-related HTTP response headers.
// Admin paths get script-src 'self'; all other paths get script-src 'none'.
func SecurityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
scriptSrc := "'none'"
if strings.HasPrefix(r.URL.Path, "/admin") {
scriptSrc = "'self'"
}
frameSrc := "'none'"
if r.URL.Path == "/stream" {
frameSrc = "https://player.twitch.tv"
}
csp := "default-src 'self'; script-src " + scriptSrc + "; style-src 'self'; img-src 'self' data:; font-src 'self'; frame-src " + frameSrc + "; frame-ancestors 'none'"
w.Header().Set("Content-Security-Policy", csp)
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
next.ServeHTTP(w, r)
})
}