-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestid.go
62 lines (50 loc) · 1.23 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
56
57
58
59
60
61
62
package beego_requestid
import (
"github.com/beego/beego"
"github.com/beego/beego/context"
"github.com/google/uuid"
)
const DefaultHeaderReqIdKey = "X-Request-Id"
type Option func(config *Config)
type GenRequestIdFunc func() string
type Config struct {
genRequestIdFunc GenRequestIdFunc
headerReqIdKey, customReqIdKey string
}
func NewFilter(opts ...Option) beego.FilterFunc {
cnf := &Config{
genRequestIdFunc: DefaultGenRequestIdFunc,
headerReqIdKey: DefaultHeaderReqIdKey,
}
for _, opt := range opts {
opt(cnf)
}
return func(c *context.Context) {
reqId := c.Request.Header.Get(cnf.headerReqIdKey)
if reqId == "" {
reqId = cnf.genRequestIdFunc()
c.Request.Header.Add(cnf.headerReqIdKey, reqId)
}
if cnf.customReqIdKey != "" {
c.Input.SetData(cnf.customReqIdKey, reqId)
}
}
}
func WithGenRequestIdFunc(genFunc GenRequestIdFunc) Option {
return func(config *Config) {
config.genRequestIdFunc = genFunc
}
}
func WithHeaderReqIdKey(key string) Option {
return func(config *Config) {
config.headerReqIdKey = key
}
}
func WithCustomReqIdKey(key string) Option {
return func(config *Config) {
config.customReqIdKey = key
}
}
func DefaultGenRequestIdFunc() string {
return uuid.NewString()
}