...
1 package request
2
3 import (
4 "context"
5
6 "github.com/gin-gonic/gin"
7
8 "edge-infra.dev/pkg/edge/audit"
9 )
10
11 type (
12
13 URLCtxKey struct{}
14
15 MethodCtxKey struct{}
16
17 CorrelationIDCtxKey struct{}
18
19 UserAgentCtxKey struct{}
20
21 IPCtxKey struct{}
22 )
23
24
25 func NewRequestMiddleware() gin.HandlerFunc {
26 return func(c *gin.Context) {
27 ctx := context.WithValue(c.Request.Context(), URLCtxKey{}, c.Request.URL.String())
28 ctx = context.WithValue(ctx, MethodCtxKey{}, c.Request.Method)
29 ctx = context.WithValue(ctx, CorrelationIDCtxKey{}, c.Request.Header.Get(audit.AuditIdentifierHeader))
30 ctx = context.WithValue(ctx, UserAgentCtxKey{}, c.Request.UserAgent())
31 ctx = context.WithValue(ctx, IPCtxKey{}, c.ClientIP())
32 c.Request = c.Request.WithContext(ctx)
33 c.Next()
34 }
35 }
36
37
38 func FromContext(ctx context.Context, key any) string {
39 val := ctx.Value(key)
40 if val == nil {
41 return ""
42 }
43 return val.(string)
44 }
45
View as plain text