Files
vectordns-server/internal/middleware/apikey.go
2026-02-24 13:44:34 -05:00

31 lines
643 B
Go

package middleware
import (
"encoding/json"
"net/http"
)
func APIKey(key string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if key == "" {
next.ServeHTTP(w, r)
return
}
provided := r.Header.Get("X-API-Key")
if provided != key {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "invalid or missing API key",
"code": "UNAUTHORIZED",
})
return
}
next.ServeHTTP(w, r)
})
}
}