...

Source file src/github.com/gin-contrib/requestid/requestid.go

Documentation: github.com/gin-contrib/requestid

     1  package requestid
     2  
     3  import (
     4  	"github.com/gin-gonic/gin"
     5  	"github.com/google/uuid"
     6  )
     7  
     8  var headerXRequestID string
     9  
    10  // Config defines the config for RequestID middleware
    11  type config struct {
    12  	// Generator defines a function to generate an ID.
    13  	// Optional. Default: func() string {
    14  	//   return uuid.New().String()
    15  	// }
    16  	generator Generator
    17  	headerKey HeaderStrKey
    18  	handler   Handler
    19  }
    20  
    21  // New initializes the RequestID middleware.
    22  func New(opts ...Option) gin.HandlerFunc {
    23  	cfg := &config{
    24  		generator: func() string {
    25  			return uuid.New().String()
    26  		},
    27  		headerKey: "X-Request-ID",
    28  	}
    29  
    30  	for _, opt := range opts {
    31  		opt(cfg)
    32  	}
    33  
    34  	return func(c *gin.Context) {
    35  		// Get id from request
    36  		rid := c.GetHeader(string(cfg.headerKey))
    37  		if rid == "" {
    38  			rid = cfg.generator()
    39  		}
    40  		headerXRequestID = string(cfg.headerKey)
    41  		if cfg.handler != nil {
    42  			cfg.handler(c, rid)
    43  		}
    44  		// Set the id to ensure that the requestid is in the response
    45  		c.Header(headerXRequestID, rid)
    46  		c.Next()
    47  	}
    48  }
    49  
    50  // Get returns the request identifier
    51  func Get(c *gin.Context) string {
    52  	return c.Writer.Header().Get(headerXRequestID)
    53  }
    54  

View as plain text