Files
wb-mock/internal/middleware/auth.go
2026-07-23 19:02:03 +03:00

34 lines
701 B
Go

package middleware
import (
"encoding/json"
"net/http"
)
func Auth(expectedAPIKey string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
apiKey := r.Header.Get("Authorization")
if apiKey == "" {
writeError(w, 401, "missing credentials: Authorization header is required")
return
}
if expectedAPIKey != "" && apiKey != expectedAPIKey {
writeError(w, 403, "invalid api key")
return
}
next(w, r)
}
}
func writeError(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]any{
"code": code,
"message": msg,
})
}