Files
novatask/internal/middleware/apikeycheck_middleware.go
2025-01-06 19:45:03 +08:00

35 lines
786 B
Go

package middleware
import (
"errors"
"net/http"
"nova_task/internal/model"
)
type ApiKeyCheckMiddleware struct {
conf model.NhSystemConfigModel
}
func NewApiKeyCheckMiddleware(conf model.NhSystemConfigModel) *ApiKeyCheckMiddleware {
return &ApiKeyCheckMiddleware{conf: conf}
}
func (m *ApiKeyCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key, err := m.conf.GetCarvApiKey(r.Context())
if err != nil {
if !errors.Is(err, model.ErrNotFound) {
http.Error(w, "system error", http.StatusInternalServerError)
return
}
}
apiKey := r.Header.Get("x-api-key")
if apiKey == "" || apiKey != key {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
return
}
next(w, r)
}
}