-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhelpers.go.tmpl
130 lines (103 loc) · 2.46 KB
/
helpers.go.tmpl
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
{{define "helpers"}}
{{ $opts := .Opts -}}
//
// Helpers
//
type method struct {
name string
service string
annotations map[string]string
}
func (m method)Name() string {
return m.name
}
func (m method)Service() string {
return m.service
}
func (m method)Annotations() map[string]string {
res := make(map[string]string, len(m.annotations))
for k, v := range m.annotations {
res[k] = v
}
return res
}
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "webrpc context value " + k.name
}
var (
{{- if $opts.client}}
HTTPClientRequestHeadersCtxKey = &contextKey{"HTTPClientRequestHeaders"}
{{- end}}
{{- if $opts.server}}
HTTPResponseWriterCtxKey = &contextKey{"HTTPResponseWriter"}
{{ end}}
HTTPRequestCtxKey = &contextKey{"HTTPRequest"}
ServiceNameCtxKey = &contextKey{"ServiceName"}
MethodNameCtxKey = &contextKey{"MethodName"}
)
func ServiceNameFromContext(ctx context.Context) string {
service, _ := ctx.Value(ServiceNameCtxKey).(string)
return service
}
func MethodNameFromContext(ctx context.Context) string {
method, _ := ctx.Value(MethodNameCtxKey).(string)
return method
}
func RequestFromContext(ctx context.Context) *http.Request {
r, _ := ctx.Value(HTTPRequestCtxKey).(*http.Request)
return r
}
func MethodCtx(ctx context.Context) (method, bool) {
req := RequestFromContext(ctx)
if req == nil {
return method{}, false
}
m, ok := methods[req.URL.Path]
if !ok {
return method{}, false
}
return m, true
}
{{ if $opts.server}}
func ResponseWriterFromContext(ctx context.Context) http.ResponseWriter {
w, _ := ctx.Value(HTTPResponseWriterCtxKey).(http.ResponseWriter)
return w
}
{{- end}}
{{- if and $opts.fixEmptyArrays $opts.server}}
// Copied from https://github.com/golang-cz/nilslice
func initializeNilSlices(obj interface{}) interface{} {
v := reflect.ValueOf(obj)
initializeNils(v)
return obj
}
func initializeNils(v reflect.Value) {
// Dereference pointer(s).
for v.Kind() == reflect.Ptr && !v.IsNil() {
v = v.Elem()
}
if v.Kind() == reflect.Slice {
// Initialize a nil slice.
if v.IsNil() && v.CanSet() {
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
return
}
// Recursively iterate over slice items.
for i := 0; i < v.Len(); i++ {
item := v.Index(i)
initializeNils(item)
}
}
// Recursively iterate over struct fields.
if v.Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
initializeNils(field)
}
}
}
{{- end -}}
{{- end -}}