-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhrpc.go
More file actions
227 lines (197 loc) · 5.06 KB
/
hrpc.go
File metadata and controls
227 lines (197 loc) · 5.06 KB
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package hrpc
import (
"net/http"
"reflect"
)
// Decoder is the request decoder
type Decoder func(*http.Request, any) error
// Encoder is the response encoder
type Encoder func(http.ResponseWriter, *http.Request, any)
// ErrorEncoder is the error response encoder
type ErrorEncoder func(http.ResponseWriter, *http.Request, error)
// Manager is the hrpc manager
type Manager struct {
Decoder Decoder
Encoder Encoder
ErrorEncoder ErrorEncoder
Validate bool // set to true to validate request after decode using Validatable interface
onErrorFuncs []func(http.ResponseWriter, *http.Request, any, error)
onOKFuncs []func(http.ResponseWriter, *http.Request, any, any)
}
func (m *Manager) decoder() Decoder {
if m.Decoder == nil {
return func(*http.Request, any) error { return nil }
}
return m.Decoder
}
func (m *Manager) encoder() Encoder {
if m.Encoder == nil {
return func(http.ResponseWriter, *http.Request, any) {}
}
return m.Encoder
}
func (m *Manager) errorEncoder() ErrorEncoder {
if m.ErrorEncoder == nil {
return func(http.ResponseWriter, *http.Request, error) {}
}
return m.ErrorEncoder
}
// OnError calls f when error
func (m *Manager) OnError(f func(w http.ResponseWriter, r *http.Request, req any, err error)) {
m.onErrorFuncs = append(m.onErrorFuncs, f)
}
// OnOK calls f before encode ok response
func (m *Manager) OnOK(f func(w http.ResponseWriter, r *http.Request, req any, res any)) {
m.onOKFuncs = append(m.onOKFuncs, f)
}
// Validatable interface
type Validatable interface {
Valid() error
}
type mapIndex int
const (
_ mapIndex = iota
miContext // context.Context
miRequest // *http.Request
miResponseWriter // http.ResponseWriter
miAny // any
miError // error
)
const (
strContext = "context.Context"
strRequest = "*http.Request"
strResponseWriter = "http.ResponseWriter"
strError = "error"
)
func setOrPanic(m map[mapIndex]int, k mapIndex, v int) {
if _, exists := m[k]; exists {
panic("hrpc: duplicate input type")
}
m[k] = v
}
func (m *Manager) encodeAndHookError(w http.ResponseWriter, r *http.Request, req any, err error) {
m.errorEncoder()(w, r, err)
for _, f := range m.onErrorFuncs {
f(w, r, req, err)
}
}
// Handler func,
// f must be a function which have at least 2 inputs and 2 outputs.
// first input must be a context.
// second input can be anything which will pass to RequestDecoder function.
// first output must be the result which will pass to success handler.
// second output must be an error interface which will pass to error handler if not nil.
func (m *Manager) Handler(f any) http.Handler {
fv := reflect.ValueOf(f)
ft := fv.Type()
if ft.Kind() != reflect.Func {
panic("hrpc: f must be a function")
}
// build mapIn
numIn := ft.NumIn()
mapIn := make(map[mapIndex]int)
for i := 0; i < numIn; i++ {
fi := ft.In(i)
// assume this is grpc call options
if fi.Kind() == reflect.Slice && i == numIn-1 {
numIn--
break
}
switch fi.String() {
case strContext:
setOrPanic(mapIn, miContext, i)
case strRequest:
setOrPanic(mapIn, miRequest, i)
case strResponseWriter:
setOrPanic(mapIn, miResponseWriter, i)
default:
setOrPanic(mapIn, miAny, i)
}
}
// build mapOut
numOut := ft.NumOut()
mapOut := make(map[mapIndex]int)
for i := 0; i < numOut; i++ {
switch ft.Out(i).String() {
case strError:
setOrPanic(mapOut, miError, i)
default:
setOrPanic(mapOut, miAny, i)
}
}
var (
infType reflect.Type
infPtr bool
)
if i, ok := mapIn[miAny]; ok {
infType = ft.In(i)
if infType.Kind() == reflect.Ptr {
infType = infType.Elem()
infPtr = true
}
}
encoder := m.encoder()
decoder := m.decoder()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
req any
res any
)
vIn := make([]reflect.Value, numIn)
// inject context
if i, ok := mapIn[miContext]; ok {
vIn[i] = reflect.ValueOf(r.Context())
}
// inject request interface
if i, ok := mapIn[miAny]; ok {
rfReq := reflect.New(infType)
req = rfReq.Interface()
err := decoder(r, req)
if err != nil {
m.encodeAndHookError(w, r, req, err)
return
}
if m.Validate {
if req, ok := req.(Validatable); ok {
err = req.Valid()
if err != nil {
m.encodeAndHookError(w, r, req, err)
return
}
}
}
if infPtr {
vIn[i] = rfReq
} else {
vIn[i] = rfReq.Elem()
}
}
// inject request
if i, ok := mapIn[miRequest]; ok {
vIn[i] = reflect.ValueOf(r)
}
// inject response writer
if i, ok := mapIn[miResponseWriter]; ok {
vIn[i] = reflect.ValueOf(w)
}
vOut := fv.Call(vIn)
// check error
if i, ok := mapOut[miError]; ok {
if vErr := vOut[i]; !vErr.IsNil() {
if err, ok := vErr.Interface().(error); ok && err != nil {
m.encodeAndHookError(w, r, req, err)
return
}
}
}
// check response
if i, ok := mapOut[miAny]; ok {
res = vOut[i].Interface()
encoder(w, r, res)
}
// run ok hooks
for _, f := range m.onOKFuncs {
f(w, r, req, res)
}
})
}