-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.go
63 lines (53 loc) · 1.72 KB
/
context.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
63
package ginmiddleware
import (
"context"
"net/http"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
ContextKey = "contextMetaKey"
)
type ContextMetaKey string
type ContextMetaData struct {
Key string
Value string
}
// GetContextMetaData get GetContextMetaData slice from incoming context
func GetContextMetaData(ctx context.Context) []ContextMetaData {
if ctxMetas, ok := ctx.Value(ContextMetaKey(ContextKey)).([]ContextMetaData); ok {
return ctxMetas
}
return make([]ContextMetaData, 0)
}
// WithMoreContextMeta add extra ContextMetaData to incoming context
func WithMoreContextMeta(ctx context.Context, data ...ContextMetaData) context.Context {
rawData := GetContextMetaData(ctx)
rawData = append(rawData, data...)
newCtx := context.WithValue(ctx, ContextMetaKey(ContextKey), rawData)
return newCtx
}
// CtxLogger put the ContextMetaData of incoming context into log
func CtxLogger(ctx context.Context) *zerolog.Logger {
data := GetContextMetaData(ctx)
logContext := log.With()
for i := range data {
logContext = logContext.Str(data[i].Key, data[i].Value)
}
logger := logContext.Logger()
return &logger
}
func InjectContextRequestHeader(ctx context.Context, req *http.Request) {
ctxMetas := GetContextMetaData(ctx)
for i := range ctxMetas {
ctxMeta := ctxMetas[i]
req.Header.Add(ctxMeta.Key, ctxMeta.Value)
}
}
// NewContextWithMeta new a context with incoming context metadata
// when we want to run a go routine in background, we should use this function
// and also can get those metadata from output context
func NewContextWithMeta(ctx context.Context) context.Context {
rawData := GetContextMetaData(ctx)
return context.WithValue(context.Background(), ContextMetaKey(ContextKey), rawData)
}