-
Notifications
You must be signed in to change notification settings - Fork 477
/
Copy pathctxkit.go
69 lines (59 loc) · 1.66 KB
/
ctxkit.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
64
65
66
67
68
69
package ctxkit
import (
"context"
"github.com/gin-gonic/gin"
"github.com/gogf/gf/util/gconv"
"google.golang.org/grpc/metadata"
"net/http"
)
type ctxHeaderKey struct{}
func (ctxHeaderKey) String() string {
return "Header-Ctx-Key"
}
func SetHeaderMiddleware(c *gin.Context) {
c.Request = c.Request.WithContext(SetValue(c.Request.Context(), ctxHeaderKey{}, c.Request.Header))
c.Next()
}
func AppendHeader(ctx context.Context, key string, value interface{}) context.Context {
header := make(http.Header)
if value := GetValue(ctx, ctxHeaderKey{}); value != nil {
if err := gconv.Struct(value, &header); err != nil {
return ctx
}
}
header.Add(key, gconv.String(value))
return SetValue(ctx, ctxHeaderKey{}, header)
}
func SetValue(ctx context.Context, key interface{}, value interface{}) context.Context {
newCtx := context.WithValue(ctx, key, value)
md := metadata.New(map[string]string{
gconv.String(key): gconv.String(value),
})
return metadata.NewOutgoingContext(newCtx, md)
}
func GetValue(ctx context.Context, key interface{}) interface{} {
if value := ctx.Value(key); value != nil {
return value
}
if md, ok := metadata.FromIncomingContext(ctx); ok {
if values := md.Get(gconv.String(key)); len(values) > 0 {
return values[0]
}
}
if md, ok := metadata.FromOutgoingContext(ctx); ok {
if values := md.Get(gconv.String(key)); len(values) > 0 {
return values[0]
}
}
return nil
}
func GetHeader(ctx context.Context, key string) interface{} {
if value := GetValue(ctx, ctxHeaderKey{}); value != nil {
var header http.Header
if err := gconv.Struct(value, &header); err != nil {
return nil
}
return header.Get(key)
}
return nil
}