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" ) 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) r = r.WithContext(ctx) next.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func ContextBus(ctx context.Context) (bus.Bus, bool) { 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) { 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) { 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) { value, ok := ctx.Value(key).(T) if !ok { return *new(T), false } return value, true }