-
Notifications
You must be signed in to change notification settings - Fork 8
/
helpers.go.tmpl
113 lines (90 loc) · 2.19 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
{{define "helpers"}}
{{ $opts := .Opts -}}
//
// Helpers
//
type method struct {
Name string
Service string
Annotations map[string]string
}
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 -}}