-
Notifications
You must be signed in to change notification settings - Fork 20
/
requestid.go
55 lines (47 loc) · 1.12 KB
/
requestid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package requestid
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
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 uuid.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 uuid.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)
}