-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgateway_annotator.go
91 lines (78 loc) · 1.77 KB
/
gateway_annotator.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package metadata
import (
"context"
"net/http"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc/metadata"
)
func GatewayHeaderMatcherFunc(withDefault bool, opts ...Option) runtime.HeaderMatcherFunc {
o := evaluateOptions(opts)
return func(key string) (string, bool) {
if withDefault {
if k, ok := runtime.DefaultHeaderMatcher(key); ok {
return k, ok
}
}
if newKey, ok := o.headers[key]; ok {
if newKey == "" {
return key, ok
} else {
return newKey, ok
}
}
for prefix, newPrefix := range o.prefixes {
if strings.HasPrefix(key, prefix) {
newKey := key
if newPrefix != prefix {
newKey = strings.Replace(key, prefix, newPrefix, 1)
}
return newKey, true
}
}
return "", false
}
}
func GatewayMetadataAnnotator(opts ...Option) func(context.Context, *http.Request) metadata.MD {
o := evaluateOptions(opts)
return func(ctx context.Context, req *http.Request) metadata.MD {
kv := []string{}
if len(o.prefixes) > 0 {
for k, _ := range req.Header {
v := req.Header.Get(k)
if v == "" {
continue
}
if newKey, ok := o.headers[k]; ok {
if newKey == "" {
kv = append(kv, k, v)
} else {
kv = append(kv, newKey, v)
}
continue
}
for prefix, newPrefix := range o.prefixes {
if strings.HasPrefix(k, prefix) {
newKey := k
if newPrefix != prefix {
newKey = strings.Replace(k, prefix, newPrefix, 1)
}
kv = append(kv, newKey, v)
break
}
}
}
} else {
for k, newKey := range o.headers {
if v := req.Header.Get(k); v != "" {
if newKey == "" {
kv = append(kv, k, v)
} else {
kv = append(kv, newKey, v)
}
}
}
}
return metadata.Pairs(kv...)
}
}