-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.go
More file actions
247 lines (209 loc) · 6.24 KB
/
bind.go
File metadata and controls
247 lines (209 loc) · 6.24 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package web
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"go-spring.dev/web/binding"
)
type Renderer interface {
Render(ctx *Context, err error, result interface{})
}
type RendererFunc func(ctx *Context, err error, result interface{})
func (fn RendererFunc) Render(ctx *Context, err error, result interface{}) {
fn(ctx, err, result)
}
// Bind convert fn to HandlerFunc.
//
// func(ctx context.Context)
//
// func(ctx context.Context) R
//
// func(ctx context.Context) error
//
// func(ctx context.Context, req T) R
//
// func(ctx context.Context, req T) error
//
// func(ctx context.Context, req T) (R, error)
//
// func(writer http.ResponseWriter, request *http.Request)
func Bind(fn interface{}, render Renderer) http.HandlerFunc {
fnValue := reflect.ValueOf(fn)
fnType := fnValue.Type()
switch h := fn.(type) {
case http.HandlerFunc:
return warpContext(h)
case http.Handler:
return warpContext(h.ServeHTTP)
case func(http.ResponseWriter, *http.Request):
return warpContext(h)
default:
// valid func
if err := validMappingFunc(fnType); nil != err {
panic(err)
}
}
firstOutIsErrorType := 1 == fnType.NumOut() && isErrorType(fnType.Out(0))
return func(writer http.ResponseWriter, request *http.Request) {
// param of context
webCtx := &Context{Writer: writer, Request: request}
ctx := WithContext(request.Context(), webCtx)
defer func() {
if nil != request.MultipartForm {
_ = request.MultipartForm.RemoveAll()
}
_ = request.Body.Close()
}()
var returnValues []reflect.Value
var err error
ctxValue := reflect.ValueOf(ctx)
switch fnType.NumIn() {
case 1:
returnValues = fnValue.Call([]reflect.Value{ctxValue})
case 2:
paramType := fnType.In(1)
pointer := false
if reflect.Ptr == paramType.Kind() {
paramType = paramType.Elem()
pointer = true
}
// new param instance with paramType.
paramValue := reflect.New(paramType)
// bind paramValue with request
if err = binding.Bind(paramValue.Interface(), webCtx); nil != err {
break
}
if !pointer {
paramValue = paramValue.Elem()
}
returnValues = fnValue.Call([]reflect.Value{ctxValue, paramValue})
default:
panic("unreachable here")
}
var result interface{}
if nil == err {
switch len(returnValues) {
case 0:
// nothing
return
case 1:
if firstOutIsErrorType {
err, _ = returnValues[0].Interface().(error)
} else {
result = returnValues[0].Interface()
}
case 2:
// check error
result = returnValues[0].Interface()
err, _ = returnValues[1].Interface().(error)
default:
panic("unreachable here")
}
}
// render response
render.Render(webCtx, err, result)
}
}
func validMappingFunc(fnType reflect.Type) error {
// func(ctx context.Context)
// func(ctx context.Context) R
// func(ctx context.Context) error
// func(ctx context.Context, req T) R
// func(ctx context.Context, req T) error
// func(ctx context.Context, req T) (R, error)
if !isFuncType(fnType) {
return fmt.Errorf("%s: not a func", fnType.String())
}
if fnType.NumIn() < 1 || fnType.NumIn() > 2 {
return fmt.Errorf("%s: expect func(ctx context.Context, [T]) [R, error]", fnType.String())
}
if fnType.NumOut() > 2 {
return fmt.Errorf("%s: expect func(ctx context.Context, [T]) [(R, error)]", fnType.String())
}
if !isContextType(fnType.In(0)) {
return fmt.Errorf("%s: expect func(ctx context.Context, [T]) [(R, error)", fnType.String())
}
if fnType.NumIn() > 1 {
argType := fnType.In(1)
if !(reflect.Struct == argType.Kind() || (reflect.Ptr == argType.Kind() && reflect.Struct == argType.Elem().Kind())) {
return fmt.Errorf("%s: input param type (%s) must be struct/*struct", fnType.String(), argType.String())
}
}
switch fnType.NumOut() {
case 0: // nothing
case 1: // R | error
case 2: // (R, error)
if isErrorType(fnType.Out(0)) {
return fmt.Errorf("%s: expect func(...) (R, error)", fnType.String())
}
if !isErrorType(fnType.Out(1)) {
return fmt.Errorf("%s: expect func(...) (R, error)", fnType.String())
}
}
return nil
}
func warpContext(handler http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
webCtx := &Context{Writer: writer, Request: request}
handler.ServeHTTP(writer, request.WithContext(WithContext(request.Context(), webCtx)))
}
}
// errorType the reflection type of error.
var errorType = reflect.TypeOf((*error)(nil)).Elem()
// contextType the reflection type of context.Context.
var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
// IsFuncType returns whether `t` is func type.
func isFuncType(t reflect.Type) bool {
return t.Kind() == reflect.Func
}
// IsErrorType returns whether `t` is error type.
func isErrorType(t reflect.Type) bool {
return t == errorType || t.Implements(errorType)
}
// IsContextType returns whether `t` is context.Context type.
func isContextType(t reflect.Type) bool {
return t == contextType || t.Implements(contextType)
}
// JsonRender is default Render
func JsonRender() RendererFunc {
return func(ctx *Context, err error, result interface{}) {
var code = 0
var message = ""
if nil != err {
var e HttpError
if errors.As(err, &e) {
code = e.Code
message = e.Message
} else {
code = http.StatusInternalServerError
message = err.Error()
if errors.Is(err, binding.ErrBinding) || errors.Is(err, binding.ErrValidate) {
code = http.StatusBadRequest
}
}
}
type JsonResponse struct {
Code int `json:"code"`
Message string `json:"message,omitempty"`
Data interface{} `json:"data"`
}
_ = ctx.JSON(http.StatusOK, JsonResponse{Code: code, Message: message, Data: result})
}
}