...

Source file src/edge-infra.dev/pkg/edge/api/middleware/request/request.go

Documentation: edge-infra.dev/pkg/edge/api/middleware/request

     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  	// URLCtxKey
    13  	URLCtxKey struct{}
    14  	// MethodCtxKey
    15  	MethodCtxKey struct{}
    16  	// CorrelationIDCtxKey
    17  	CorrelationIDCtxKey struct{}
    18  	// UserAgentCtxKey
    19  	UserAgentCtxKey struct{}
    20  	// IPCtxKey
    21  	IPCtxKey struct{}
    22  )
    23  
    24  // NewRequestMiddleware adds the client user agent to the ctx and returns a gin middleware.
    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  // FromContext returns the request key value from a context.
    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