package httputil import ( "encoding/json" "net/http" "strings" ) func WriteJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func WriteError(w http.ResponseWriter, status int, msg string) { WriteJSON(w, status, map[string]string{"error": msg}) } // AuthMiddleware validates the Authorization: Bearer header. // If secretKey is empty, auth is disabled and all requests pass through. // /health is always exempt. func AuthMiddleware(secretKey string, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if secretKey == "" || r.URL.Path == "/health" { next.ServeHTTP(w, r) return } token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || token != secretKey { WriteError(w, http.StatusUnauthorized, "unauthorized") return } next.ServeHTTP(w, r) }) }