Files
schemas/middleware/apikey.go
T

40 lines
799 B
Go

package middleware
import (
"context"
"fmt"
"net/http"
)
const (
ApiKey = ContextKey("apikey")
)
func NewApiKey() *ApiKeyMiddleware {
return &ApiKeyMiddleware{}
}
type ApiKeyMiddleware struct{}
func (m *ApiKeyMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("x-api-key")
if len(header) == 0 {
next.ServeHTTP(w, r)
} else {
ctx := context.WithValue(r.Context(), ApiKey, header)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}
func ApiKeyFromContext(ctx context.Context) (string, error) {
if value := ctx.Value(ApiKey); value != nil {
if u, ok := value.(string); ok {
return u, nil
}
return "", fmt.Errorf("current API-key is in wrong format")
}
return "", nil
}