edge/pkg/http/context.go

76 lines
1.9 KiB
Go
Raw Normal View History

2023-11-28 16:35:49 +01:00
package http
import (
"context"
"net/http"
"forge.cadoles.com/arcad/edge/pkg/bus"
)
type contextKey string
var (
contextKeyBus contextKey = "bus"
contextKeyHTTPRequest contextKey = "httpRequest"
contextKeyHTTPClient contextKey = "httpClient"
contextKeySessionID contextKey = "sessionId"
2023-11-28 16:35:49 +01:00
)
func (h *Handler) contextMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = WithContextBus(ctx, h.bus)
ctx = WithContextHTTPRequest(ctx, r)
ctx = WithContextHTTPClient(ctx, h.httpClient)
2023-11-28 16:35:49 +01:00
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func ContextBus(ctx context.Context) (bus.Bus, bool) {
2023-11-28 16:35:49 +01:00
return contextValue[bus.Bus](ctx, contextKeyBus)
}
func WithContextBus(parent context.Context, bus bus.Bus) context.Context {
return context.WithValue(parent, contextKeyBus, bus)
}
func ContextHTTPRequest(ctx context.Context) (*http.Request, bool) {
2023-11-28 16:35:49 +01:00
return contextValue[*http.Request](ctx, contextKeyHTTPRequest)
}
func WithContextHTTPRequest(parent context.Context, request *http.Request) context.Context {
return context.WithValue(parent, contextKeyHTTPRequest, request)
}
func ContextHTTPClient(ctx context.Context) (*http.Client, bool) {
2023-11-28 16:35:49 +01:00
return contextValue[*http.Client](ctx, contextKeyHTTPClient)
}
func WithContextHTTPClient(parent context.Context, client *http.Client) context.Context {
return context.WithValue(parent, contextKeyHTTPClient, client)
}
func ContextSessionID(ctx context.Context) (string, bool) {
return contextValue[string](ctx, contextKeySessionID)
}
func WithContextSessionID(parent context.Context, sessionID string) context.Context {
return context.WithValue(parent, contextKeySessionID, sessionID)
}
func contextValue[T any](ctx context.Context, key any) (T, bool) {
2023-11-28 16:35:49 +01:00
value, ok := ctx.Value(key).(T)
if !ok {
return *new(T), false
2023-11-28 16:35:49 +01:00
}
return value, true
2023-11-28 16:35:49 +01:00
}