package http import ( "context" "net/http" "forge.cadoles.com/arcad/edge/pkg/bus" "github.com/pkg/errors" ) type contextKey string var ( contextKeyBus contextKey = "bus" contextKeyHTTPRequest contextKey = "httpRequest" contextKeyHTTPClient contextKey = "httpClient" ) func (h *Handler) contextMiddleware(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ctx = context.WithValue(ctx, contextKeyBus, h.bus) ctx = context.WithValue(ctx, contextKeyHTTPRequest, r) ctx = context.WithValue(ctx, contextKeyHTTPClient, h.httpClient) r = r.WithContext(ctx) next.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func ContextBus(ctx context.Context) bus.Bus { return contextValue[bus.Bus](ctx, contextKeyBus) } func ContextHTTPRequest(ctx context.Context) *http.Request { return contextValue[*http.Request](ctx, contextKeyHTTPRequest) } func ContextHTTPClient(ctx context.Context) *http.Client { return contextValue[*http.Client](ctx, contextKeyHTTPClient) } func contextValue[T any](ctx context.Context, key any) T { value, ok := ctx.Value(key).(T) if !ok { panic(errors.Errorf("could not find key '%v' on context", key)) } return value }