-
Notifications
You must be signed in to change notification settings - Fork 1
/
gin.go
executable file
·331 lines (295 loc) · 8.2 KB
/
gin.go
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package helper
import (
"bytes"
"net/http"
"reflect"
"strings"
"sync"
"github.com/cockroachdb/errors"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
validator "github.com/go-playground/validator/v10"
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
"github.com/rs/zerolog"
)
var (
ginHelper *GinHelper
ginHelperOnce sync.Once
)
type GinHelper struct {
Bindings []GinBinding
BindingValidator binding.StructValidator
BindingErrorHandler func(*gin.Context, error)
SuccessHandler func(*gin.Context, any)
ErrorHandler func(*gin.Context, error)
}
// Gin
// - Notes: This function first call will disable the gin default validator
func Gin(options ...func(*GinHelper)) *GinHelper {
ginHelperOnce.Do(func() {
ginHelper = &GinHelper{
Bindings: []GinBinding{
NewGinDefaultBinding(),
NewGinBinding(binding.Header),
NewGinURIBinding(),
NewGinBinding(binding.Form),
NewGinBinding(binding.JSON),
},
BindingValidator: NewGinValidator(),
BindingErrorHandler: func(c *gin.Context, err error) {
c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())
},
ErrorHandler: func(c *gin.Context, err error) {
c.AbortWithStatusJSON(http.StatusInternalServerError, err.Error())
},
SuccessHandler: func(c *gin.Context, resp any) {
c.JSON(http.StatusOK, resp)
},
}
gin.DisableBindValidation()
})
for _, opt := range options {
opt(ginHelper)
}
return ginHelper
}
// SetZerologWriter set zerolog writer
// - gin.DefaultWriter
// - gin.DefaultErrorWriter
// - gin.DebugPrintRouteFunc
func (h *GinHelper) SetZerologWriter(log zerolog.Logger, lvl zerolog.Level) *GinHelper {
zw := ginZerologWriter{log: log, lvl: lvl}
zw.SetAll()
return h
}
func (h *GinHelper) Router(routes gin.IRoutes) *GinRouter {
return &GinRouter{
helper: h,
routes: routes,
}
}
type GinRouter struct {
routes gin.IRoutes
helper *GinHelper
}
func (r *GinRouter) GET(path string, handler any) *GinRouter {
return r.Handle(http.MethodGet, path, handler)
}
func (r *GinRouter) POST(path string, handler any) *GinRouter {
return r.Handle(http.MethodPost, path, handler)
}
func (r *GinRouter) Handle(method string, path string, handler any) *GinRouter {
assertHandler(handler)
v := reflect.ValueOf(handler)
t := v.Type()
request := func(c *gin.Context) ([]reflect.Value, error) {
in := make([]reflect.Value, 0, t.NumIn())
in = append(in, reflect.ValueOf(c))
if t.NumIn() == 2 {
reqV := reflect.New(t.In(1).Elem())
reqT := reqV.Elem().Type()
// check if request struct has tags
hasTags := make(map[string]bool)
hasTags["default"] = true
for i := 0; i < reqT.NumField(); i++ {
for _, b := range r.helper.Bindings {
tag := b.Name()
if hasTags[tag] {
continue
}
if _, ok := reqT.Field(i).Tag.Lookup(tag); ok {
hasTags[tag] = true
}
}
}
// call BeforeBind hook
if beforeBinding, ok := reqV.Interface().(BeforeBinding); ok {
if err := beforeBinding.BeforeBind(c); err != nil {
return nil, errors.Wrap(err, "hook BeforeBind failed")
}
}
// bind
for _, b := range r.helper.Bindings {
if !hasTags[b.Name()] {
continue
}
err := b.Bind(c, reqV.Interface())
if err != nil {
return nil, errors.Wrapf(err, "bind %s failed", b.Name())
}
}
// call AfterBind hook
if afterBinding, ok := reqV.Interface().(AfterBinding); ok {
if err := afterBinding.AfterBind(c); err != nil {
return nil, errors.Wrap(err, "hook AfterBind failed")
}
}
// call BeforeValidate hook
if beforeValidation, ok := reqV.Interface().(BeforeValidation); ok {
if err := beforeValidation.BeforeValidate(c); err != nil {
return nil, errors.Wrap(err, "hook BeforeValidate failed")
}
}
// validate
err := r.helper.BindingValidator.ValidateStruct(reqV.Elem().Interface())
if err != nil {
return nil, errors.Wrap(err, "validate failed")
}
// call AfterValidate hook
if afterValidation, ok := reqV.Interface().(AfterValidation); ok {
if err := afterValidation.AfterValidate(c); err != nil {
return nil, errors.Wrap(err, "hook AfterValidate failed")
}
}
in = append(in, reqV)
}
return in, nil
}
r.routes.Handle(method, path, func(c *gin.Context) {
in, err := request(c)
if err != nil {
r.helper.BindingErrorHandler(c, err)
return
}
out := v.Call(in)
var resp any
switch len(out) {
case 0:
return
case 1:
if errVal := out[0].Interface(); errVal != nil {
err = errVal.(error)
}
case 2:
resp = out[0].Interface()
if errVal := out[1].Interface(); errVal != nil {
err = errVal.(error)
}
default:
panic("invalid count for handler return values")
}
if err != nil {
r.helper.ErrorHandler(c, err)
return
}
if resp != nil {
r.helper.SuccessHandler(c, resp)
return
}
})
return r
}
type BeforeBinding interface {
BeforeBind(c *gin.Context) error
}
type AfterBinding interface {
AfterBind(c *gin.Context) error
}
type BeforeValidation interface {
BeforeValidate(c *gin.Context) error
}
type AfterValidation interface {
AfterValidate(c *gin.Context) error
}
type GinValidator struct {
Validate *validator.Validate
Translator locales.Translator
TranslatorRegister func(v *validator.Validate, trans ut.Translator) error
Verbose bool
utTranslator *ut.UniversalTranslator
}
var _ binding.StructValidator = (*GinValidator)(nil)
func NewGinValidator(options ...func(*GinValidator)) *GinValidator {
v := validator.New()
v.SetTagName("binding")
gv := &GinValidator{
Validate: v,
Translator: zh.New(),
TranslatorRegister: zhTranslations.RegisterDefaultTranslations,
Verbose: false,
}
for _, opt := range options {
opt(gv)
}
gv.utTranslator = ut.New(gv.Translator)
err := gv.TranslatorRegister(v, gv.utTranslator.GetFallback())
if err != nil {
panic(err)
}
return gv
}
func (v *GinValidator) ValidateStruct(obj any) error {
val := reflect.ValueOf(obj)
typ := val.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
return nil
}
err := v.Validate.Struct(obj)
if err != nil {
errs := err.(validator.ValidationErrors)
if v.Verbose {
kvTuple := make([]string, 0, len(errs))
for k, v := range errs.Translate(v.utTranslator.GetFallback()) {
kvTuple = append(kvTuple, k+"="+v)
}
return errors.Newf("[%s]", strings.Join(kvTuple, ","))
}
var buf bytes.Buffer
buf.WriteByte('[')
vSlice := make([]string, 0, len(errs))
for _, v := range errs.Translate(v.utTranslator.GetFallback()) {
vSlice = append(vSlice, v)
}
buf.WriteString(strings.Join(vSlice, ","))
buf.WriteByte(']')
return errors.New(buf.String())
}
return nil
}
func (v *GinValidator) Engine() any {
return v.Validate
}
// assertHandler checks if handler is valid
// handler must be a function
// handler's first argument must be *gin.Context
// handler's second argument must be a struct
// handler's last return value must be error
// handler's first return value must be a pointer
// example:
// - func(c *gin.Context)
// - func(c *gin.Context) error
// - func(c *gin.Context, *req) error
// - func(c *gin.Context) (*resp, error)
// - func(c *gin.Context, *req) (*resp, error)
func assertHandler(handler any) {
v := reflect.ValueOf(handler)
t := v.Type()
if t.Kind() != reflect.Func {
panic("handler must be a function")
}
if t.NumIn() == 0 || t.NumIn() > 2 {
panic("handler must have 1 or 2 arguments")
}
if t.In(0) != reflect.TypeOf(&gin.Context{}) {
panic("handler's first argument must be *gin.Context")
}
if t.NumIn() == 2 &&
(t.In(1).Kind() != reflect.Ptr || t.In(1).Elem().Kind() != reflect.Struct) {
panic("handler's second argument must be a struct pointer")
}
if t.NumOut() > 2 {
panic("handler return values count must be 2 or less")
}
if t.NumOut() != 0 && !t.Out(t.NumOut()-1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
panic("handler's last return value must be error")
}
if t.NumOut() == 2 && t.Out(0).Kind() != reflect.Ptr {
panic("handler's first return value must be a pointer")
}
}