diff --git a/gweb/requestid/options.go b/gweb/requestid/options.go new file mode 100644 index 0000000..92afe13 --- /dev/null +++ b/gweb/requestid/options.go @@ -0,0 +1,41 @@ +// +// options.go +// Copyright (C) 2023 tiglog +// +// Distributed under terms of the MIT license. +// + +package requestid + +import "github.com/gin-gonic/gin" + +// Option for queue system +type Option func(*config) + +type ( + Generator func() string + Handler func(c *gin.Context, requestID string) +) + +type HeaderStrKey string + +// WithGenerator set generator function +func WithGenerator(g Generator) Option { + return func(cfg *config) { + cfg.generator = g + } +} + +// WithCustomHeaderStrKey set custom header key for request id +func WithCustomHeaderStrKey(s HeaderStrKey) Option { + return func(cfg *config) { + cfg.headerKey = s + } +} + +// WithHandler set handler function for request id with context +func WithHandler(handler Handler) Option { + return func(cfg *config) { + cfg.handler = handler + } +} diff --git a/gweb/requestid/reqid.go b/gweb/requestid/reqid.go new file mode 100644 index 0000000..821aa0e --- /dev/null +++ b/gweb/requestid/reqid.go @@ -0,0 +1,62 @@ +// +// reqid.go +// Copyright (C) 2023 tiglog +// +// Distributed under terms of the MIT license. +// + +package requestid + +import ( + "github.com/gin-gonic/gin" + "github.com/rs/xid" +) + +var headerXRequestID string + +// Config defines the config for RequestID middleware +type config struct { + // Generator defines a function to generate an ID. + // Optional. Default: func() string { + // return xid.New().String() + // } + generator Generator + headerKey HeaderStrKey + handler Handler +} + +// New initializes the RequestID middleware. +func New(opts ...Option) gin.HandlerFunc { + cfg := &config{ + generator: func() string { + return xid.New().String() + }, + headerKey: "X-Request-ID", + } + + for _, opt := range opts { + opt(cfg) + } + + headerXRequestID = string(cfg.headerKey) + + return func(c *gin.Context) { + // Get id from request + rid := c.GetHeader(headerXRequestID) + if rid == "" { + rid = cfg.generator() + c.Request.Header.Add(headerXRequestID, rid) + } + if cfg.handler != nil { + cfg.handler(c, rid) + } + // Set the id to ensure that the requestid is in the response + c.Header(headerXRequestID, rid) + c.Next() + } +} + +// Get returns the request identifier +func Get(c *gin.Context) string { + return c.GetHeader(headerXRequestID) +}