package handler import ( "net/http" ) // AuthMiddleware returns a middleware that validates the Bearer token. func AuthMiddleware(token string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { const prefix = "Bearer " auth := r.Header.Get("Authorization") if len(auth) < len(prefix) || auth[:len(prefix)] != prefix { writeError(w, http.StatusUnauthorized, "missing or malformed Authorization header") return } if auth[len(prefix):] != token { writeError(w, http.StatusUnauthorized, "invalid token") return } next.ServeHTTP(w, r) }) } }