...
1 package grpc
2
3 import (
4 "context"
5 "encoding/base64"
6 "strings"
7
8 "google.golang.org/grpc/metadata"
9 )
10
11 const (
12 binHdrSuffix = "-bin"
13 )
14
15
16
17
18
19 type ClientRequestFunc func(context.Context, *metadata.MD) context.Context
20
21
22
23
24 type ServerRequestFunc func(context.Context, metadata.MD) context.Context
25
26
27
28
29
30 type ServerResponseFunc func(ctx context.Context, header *metadata.MD, trailer *metadata.MD) context.Context
31
32
33
34
35
36 type ClientResponseFunc func(ctx context.Context, header metadata.MD, trailer metadata.MD) context.Context
37
38
39
40 func SetRequestHeader(key, val string) ClientRequestFunc {
41 return func(ctx context.Context, md *metadata.MD) context.Context {
42 key, val := EncodeKeyValue(key, val)
43 (*md)[key] = append((*md)[key], val)
44 return ctx
45 }
46 }
47
48
49
50 func SetResponseHeader(key, val string) ServerResponseFunc {
51 return func(ctx context.Context, md *metadata.MD, _ *metadata.MD) context.Context {
52 key, val := EncodeKeyValue(key, val)
53 (*md)[key] = append((*md)[key], val)
54 return ctx
55 }
56 }
57
58
59
60 func SetResponseTrailer(key, val string) ServerResponseFunc {
61 return func(ctx context.Context, _ *metadata.MD, md *metadata.MD) context.Context {
62 key, val := EncodeKeyValue(key, val)
63 (*md)[key] = append((*md)[key], val)
64 return ctx
65 }
66 }
67
68
69 func EncodeKeyValue(key, val string) (string, string) {
70 key = strings.ToLower(key)
71 if strings.HasSuffix(key, binHdrSuffix) {
72 val = base64.StdEncoding.EncodeToString([]byte(val))
73 }
74 return key, val
75 }
76
77 type contextKey int
78
79 const (
80 ContextKeyRequestMethod contextKey = iota
81 )
82
View as plain text