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"
|
2023-11-30 19:09:51 +01:00
|
|
|
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()
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
func ContextBus(ctx context.Context) (bus.Bus, bool) {
|
2023-11-28 16:35:49 +01:00
|
|
|
return contextValue[bus.Bus](ctx, contextKeyBus)
|
|
|
|
}
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
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 {
|
2023-11-30 19:09:51 +01:00
|
|
|
return *new(T), false
|
2023-11-28 16:35:49 +01:00
|
|
|
}
|
|
|
|
|
2023-11-30 19:09:51 +01:00
|
|
|
return value, true
|
2023-11-28 16:35:49 +01:00
|
|
|
}
|