-
Notifications
You must be signed in to change notification settings - Fork 50
/
handler.go
555 lines (441 loc) · 12.9 KB
/
handler.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package httpserver
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"github.com/gin-contrib/location"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/imdario/mergo"
"github.com/justtrackio/gosoline/pkg/coffin"
"github.com/justtrackio/gosoline/pkg/mdl"
"github.com/pkg/errors"
"github.com/spf13/cast"
"google.golang.org/protobuf/proto"
)
const (
ApiViewKey = "X-Api-View"
ContentTypeHtml = "text/html; charset=utf-8"
ContentTypeJson = "application/json; charset=utf-8"
ContentTypeProtobuf = "application/x-protobuf"
)
var ErrAccessForbidden = errors.New("cant access resource")
type Request struct {
Body interface{}
ClientIp string
Cookies map[string]string
Header http.Header
Method string
Params gin.Params
Url *url.URL
}
// Don't create a response directly, use New*Response instead
type Response struct {
Body interface{}
ContentType *string // might be nil
Header http.Header
StatusCode int
}
type emptyRenderer struct{}
func (e emptyRenderer) Render(http.ResponseWriter) error {
return nil
}
func (e emptyRenderer) WriteContentType(_ http.ResponseWriter) {
}
func NewResponse(body interface{}, contentType string, statusCode int, header http.Header) *Response {
return &Response{
Body: body,
Header: header,
ContentType: &contentType,
StatusCode: statusCode,
}
}
func NewHtmlResponse(body interface{}) *Response {
return &Response{
StatusCode: http.StatusOK,
ContentType: mdl.Box(ContentTypeHtml),
Body: body,
Header: make(http.Header),
}
}
func NewJsonResponse(body interface{}) *Response {
return &Response{
StatusCode: http.StatusOK,
ContentType: mdl.Box(ContentTypeJson),
Body: body,
Header: make(http.Header),
}
}
func NewProtobufResponse(body ProtobufEncodable) (*Response, error) {
message, err := body.ToMessage()
if err != nil {
return nil, fmt.Errorf("failed to transform body to protobuf message: %w", err)
}
bytes, err := proto.Marshal(message)
if err != nil {
return nil, fmt.Errorf("failed to encode body as protobuf message: %w", err)
}
return &Response{
StatusCode: http.StatusOK,
ContentType: mdl.Box(ContentTypeProtobuf),
Body: bytes,
Header: make(http.Header),
}, nil
}
func NewRedirectResponse(url string) *Response {
header := make(http.Header)
header.Set("Location", url)
return &Response{
StatusCode: http.StatusFound,
ContentType: nil,
Body: nil,
Header: header,
}
}
func NewStatusResponse(statusCode int) *Response {
return &Response{
StatusCode: statusCode,
ContentType: nil,
Body: nil,
Header: make(http.Header),
}
}
func (r *Response) AddHeader(key string, value string) {
r.Header.Add(key, value)
}
func (r *Response) WithBody(body interface{}) *Response {
r.Body = body
return r
}
func (r *Response) WithContentType(contentType string) *Response {
r.ContentType = &contentType
return r
}
//go:generate mockery --name HandlerWithoutInput
type HandlerWithoutInput interface {
Handle(requestContext context.Context, request *Request) (response *Response, err error)
}
//go:generate mockery --name HandlerWithInput
type HandlerWithInput interface {
HandlerWithoutInput
GetInput() interface{}
}
//go:generate mockery --name HandlerWithMultipleBindings
type HandlerWithMultipleBindings interface {
HandlerWithInput
GetBindings() []binding.Binding
}
//go:generate mockery --name HandlerWithStream
type HandlerWithStream interface {
GetInput() interface{}
Handle(ginContext *gin.Context, requestContext context.Context, request *Request) (err error)
}
func CreateHandler(handler HandlerWithoutInput) gin.HandlerFunc {
return handleWithoutInput(handler, defaultErrorHandler)
}
func CreateJsonHandler(handler HandlerWithInput) gin.HandlerFunc {
return handleWithInput(handler, binding.JSON, defaultErrorHandler)
}
func CreateProtobufHandler(handler HandlerWithInput) gin.HandlerFunc {
return handleWithInput(handler, protobufBinding, defaultErrorHandler)
}
func CreateMultiPartFormHandler(handler HandlerWithInput) gin.HandlerFunc {
return handleWithMultiPartFormInput(handler, defaultErrorHandler)
}
func CreateMultipleBindingsHandler(handler HandlerWithMultipleBindings) gin.HandlerFunc {
return handleWithMultipleBindings(handler, defaultErrorHandler)
}
func CreateRawHandler(handler HandlerWithoutInput) gin.HandlerFunc {
return handleRaw(handler, defaultErrorHandler)
}
func CreateReaderHandler(handler HandlerWithoutInput) gin.HandlerFunc {
return handleReader(handler, defaultErrorHandler)
}
func CreateQueryHandler(handler HandlerWithInput) gin.HandlerFunc {
return handleWithInput(handler, binding.Query, defaultErrorHandler)
}
func CreateSseHandler(handler HandlerWithStream) gin.HandlerFunc {
return handleWithStream(handler, binding.Query, defaultErrorHandler)
}
func CreateStreamHandler(handler HandlerWithStream) gin.HandlerFunc {
return handleWithStream(handler, binding.JSON, defaultErrorHandler)
}
func CreateDownloadHandler(handler HandlerWithStream) gin.HandlerFunc {
return handleWithStream(handler, binding.Query, defaultErrorHandler)
}
func handleWithInput(handler HandlerWithInput, binding binding.Binding, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
input := handler.GetInput()
err := binding.Bind(ginCtx.Request, input)
if err != nil {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: err,
Type: gin.ErrorTypeBind,
})
return
}
handle(ginCtx, handler, input, errHandler)
}
}
func handleWithoutInput(handler HandlerWithoutInput, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
handle(ginCtx, handler, nil, errHandler)
}
}
func handleWithMultiPartFormInput(handler HandlerWithInput, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
input := handler.GetInput()
err := binding.FormMultipart.Bind(ginCtx.Request, input)
if err != nil && !errors.Is(err, http.ErrMissingFile) {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: err,
Type: gin.ErrorTypeBind,
})
return
}
handle(ginCtx, handler, input, errHandler)
}
}
func handleWithStream(handler HandlerWithStream, binding binding.Binding, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
input := handler.GetInput()
err := binding.Bind(ginCtx.Request, input)
if err != nil {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: err,
Type: gin.ErrorTypeBind,
})
return
}
ginUrl, err := parseUrl(ginCtx)
if err != nil {
handleError(ginCtx, errHandler, http.StatusInternalServerError, gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
return
}
reqCtx := ginCtx.Request.Context()
request := &Request{
Method: ginCtx.Request.Method,
Header: ginCtx.Request.Header,
Cookies: parseCookies(ginCtx.Request),
Params: ginCtx.Params,
Url: ginUrl,
Body: input,
ClientIp: ginCtx.ClientIP(),
}
err = handler.Handle(ginCtx, reqCtx, request)
if err != nil {
handleError(ginCtx, errHandler, http.StatusInternalServerError, gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
return
}
}
}
func handleWithMultipleBindings(handler HandlerWithMultipleBindings, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
input := handler.GetInput()
bindings := handler.GetBindings()
for i := 0; i < len(bindings); i++ {
err := bindings[i].Bind(ginCtx.Request, input)
if err != nil {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: err,
Type: gin.ErrorTypeBind,
})
return
}
}
handle(ginCtx, handler, input, errHandler)
}
}
func handleRaw(handler HandlerWithoutInput, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
body, err := io.ReadAll(ginCtx.Request.Body)
if err != nil {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: err,
Type: gin.ErrorTypeBind,
})
return
}
handle(ginCtx, handler, string(body), errHandler)
}
}
func handleReader(handler HandlerWithoutInput, errHandler ErrorHandler) gin.HandlerFunc {
return func(ginCtx *gin.Context) {
handle(ginCtx, handler, ginCtx.Request.Body, errHandler)
}
}
func handle(ginCtx *gin.Context, handler HandlerWithoutInput, input interface{}, errHandler ErrorHandler) {
reqCtx := ginCtx.Request.Context()
ginUrl, err := parseUrl(ginCtx)
if err != nil {
handleError(ginCtx, errHandler, http.StatusInternalServerError, gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
return
}
if isMutableInput(input) {
modErr := modifyInput(ginCtx, input)
if modErr != nil {
handleError(ginCtx, errHandler, http.StatusBadRequest, gin.Error{
Err: modErr,
Type: gin.ErrorTypePrivate,
})
return
}
}
request := &Request{
Method: ginCtx.Request.Method,
Header: ginCtx.Request.Header,
Cookies: parseCookies(ginCtx.Request),
Params: ginCtx.Params,
Url: ginUrl,
Body: input,
ClientIp: ginCtx.ClientIP(),
}
resp, err := handler.Handle(reqCtx, request)
if errors.Is(err, ErrAccessForbidden) {
handleForbidden(ginCtx, errHandler, http.StatusForbidden, gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
return
}
if err != nil {
handleError(ginCtx, errHandler, http.StatusInternalServerError, gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
return
}
writer, err := mkResponseBodyWriter(resp)
if err != nil {
handleError(ginCtx, errHandler, http.StatusInternalServerError, gin.Error{
Err: err,
Type: gin.ErrorTypeRender,
})
return
}
writeResponseHeaders(ginCtx, resp)
writer(ginCtx)
}
func isMutableInput(input interface{}) bool {
if input == nil {
return false
}
if reflect.ValueOf(input).Kind() != reflect.Pointer {
return false
}
if reflect.ValueOf(input).Elem().Kind() != reflect.Struct {
return false
}
return true
}
func parseCookies(request *http.Request) map[string]string {
result := make(map[string]string)
for _, cookie := range request.Cookies() {
result[cookie.Name] = cookie.Value
}
return result
}
func parseUrl(ctx *gin.Context) (*url.URL, error) {
ginUrl := location.Get(ctx)
if ginUrl == nil {
ginUrl = &url.URL{}
}
reqUrl := ctx.Request.URL
if reqUrl == nil {
reqUrl = &url.URL{}
}
if err := mergo.Merge(reqUrl, ginUrl); err != nil {
return nil, fmt.Errorf("could not merge urls: %w", err)
}
if ctx.Request.Host != "" {
reqUrl.Host = ctx.Request.Host
}
return reqUrl, nil
}
func handleError(ginCtx *gin.Context, errHandler ErrorHandler, statusCode int, ginError gin.Error) {
_ = ginCtx.Error(&ginError)
resp := errHandler(statusCode, ginError.Err)
writer, err := mkResponseBodyWriter(resp)
if err != nil {
panic(errors.WithMessage(err, "Error creating writer for error handler"))
}
writer(ginCtx)
}
func handleForbidden(ginCtx *gin.Context, errHandler ErrorHandler, statusCode int, ginError gin.Error) {
resp := errHandler(statusCode, ginError.Err)
writer, err := mkResponseBodyWriter(resp)
if err != nil {
panic(errors.WithMessage(err, "Error creating writer for error handler"))
}
writer(ginCtx)
}
func writeResponseHeaders(ginCtx *gin.Context, resp *Response) {
for name, values := range resp.Header {
for _, value := range values {
ginCtx.Header(name, value)
}
}
}
func mkResponseBodyWriter(resp *Response) (func(ginCtx *gin.Context), error) {
if resp.ContentType == nil {
return withRecover(func(ginCtx *gin.Context) {
ginCtx.Render(resp.StatusCode, emptyRenderer{})
}), nil
}
if *resp.ContentType == ContentTypeJson {
return withRecover(func(ginCtx *gin.Context) {
ginCtx.JSON(resp.StatusCode, resp.Body)
}), nil
}
if b, ok := resp.Body.([]byte); ok {
return withRecover(func(ginCtx *gin.Context) {
ginCtx.Data(resp.StatusCode, *resp.ContentType, b)
}), nil
}
data, err := cast.ToStringE(resp.Body)
if err != nil {
return nil, err
}
return withRecover(func(ginCtx *gin.Context) {
ginCtx.Data(resp.StatusCode, *resp.ContentType, []byte(data))
}), nil
}
type ResponseBodyWriterError struct {
Err error
}
func (e ResponseBodyWriterError) Error() string {
return fmt.Sprintf("handler response body writer error: %s", e.Err.Error())
}
func (e ResponseBodyWriterError) Unwrap() error {
return e.Err
}
func (e ResponseBodyWriterError) Is(err error) bool {
_, ok := err.(ResponseBodyWriterError)
return ok
}
func withRecover(f func(ginCtx *gin.Context)) func(ginCtx *gin.Context) {
return func(ginCtx *gin.Context) {
defer func() {
err := coffin.ResolveRecovery(recover())
if err == nil {
return
}
// When building the response body, should there be an e.g. broken pipe error, we do not want to
// log an application error. Instead, RecoveryWithSentry within middleware_recover will log a warning instead
panic(ResponseBodyWriterError{Err: err})
}()
f(ginCtx)
}
}