/
metadata.go
47 lines (41 loc) · 1.21 KB
/
metadata.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
package gateway
import (
"net/http"
"net/textproto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc/metadata"
)
// headerMatcher extends runtime.DefaultHeaderMatcher by also injecting headers
// that are not-standard, but in use in Automate.
func headerMatcher(key string) (string, bool) {
// default behavior
if key, ok := runtime.DefaultHeaderMatcher(key); ok {
return key, ok
}
if isAutomateHeader(key) {
return runtime.MetadataPrefix + key, true
}
return "", false
}
func isAutomateHeader(hdr string) bool {
switch textproto.CanonicalMIMEHeaderKey(hdr) {
case "X-Data-Collector-Token", "Api-Token", "X-Client-Cert", "Projects":
return true
}
return false
}
// metadataFromRequest constructs a metadata object to be passed into the
// context of a grpc call (via `metadata.NewOutgoingContext`). It mimics
// what grpc-gateway does and is only used for the custom, handcrafted
// endpoints defined in `gateway/services.go`.
func metadataFromRequest(r *http.Request) metadata.MD {
var pairs []string
for key, vals := range r.Header {
for _, val := range vals {
if h, ok := headerMatcher(key); ok {
pairs = append(pairs, h, val)
}
}
}
return metadata.Pairs(pairs...)
}