Files
schemas/middleware/apikey.go
T

40 lines
799 B
Go
Raw Normal View History

2022-10-09 15:23:52 +02:00
package middleware
import (
"context"
"fmt"
"net/http"
)
const (
ApiKey = ContextKey("apikey")
)
2023-04-27 07:09:10 +02:00
func NewApiKey() *ApiKeyMiddleware {
return &ApiKeyMiddleware{}
2022-10-09 15:23:52 +02:00
}
2023-04-27 07:09:10 +02:00
type ApiKeyMiddleware struct{}
2022-10-09 15:23:52 +02:00
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))
}
})
}
2023-04-27 07:09:10 +02:00
func ApiKeyFromContext(ctx context.Context) (string, error) {
2022-10-09 15:23:52 +02:00
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")
}
2023-04-27 07:09:10 +02:00
return "", nil
2022-10-09 15:23:52 +02:00
}