package request import ( "context" "github.com/gin-gonic/gin" "edge-infra.dev/pkg/edge/audit" ) type ( // URLCtxKey URLCtxKey struct{} // MethodCtxKey MethodCtxKey struct{} // CorrelationIDCtxKey CorrelationIDCtxKey struct{} // UserAgentCtxKey UserAgentCtxKey struct{} // IPCtxKey IPCtxKey struct{} ) // NewRequestMiddleware adds the client user agent to the ctx and returns a gin middleware. func NewRequestMiddleware() gin.HandlerFunc { return func(c *gin.Context) { ctx := context.WithValue(c.Request.Context(), URLCtxKey{}, c.Request.URL.String()) ctx = context.WithValue(ctx, MethodCtxKey{}, c.Request.Method) ctx = context.WithValue(ctx, CorrelationIDCtxKey{}, c.Request.Header.Get(audit.AuditIdentifierHeader)) ctx = context.WithValue(ctx, UserAgentCtxKey{}, c.Request.UserAgent()) ctx = context.WithValue(ctx, IPCtxKey{}, c.ClientIP()) c.Request = c.Request.WithContext(ctx) c.Next() } } // FromContext returns the request key value from a context. func FromContext(ctx context.Context, key any) string { val := ctx.Value(key) if val == nil { return "" } return val.(string) }