-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_parse_model.go
78 lines (68 loc) · 2.43 KB
/
middleware_parse_model.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
package uhttp
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"reflect"
)
// ParseModel parses and adds a model from a requestbody if wanted
func parseModelMiddleware(u *UHTTP, handlerOpts handlerOptions, postModel interface{}, getModel interface{}, deleteModel interface{}) func(next http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var reflectModel reflect.Value
doParsing := false
if r.Method == http.MethodPost && postModel != nil {
reflectModel = reflect.New(reflect.TypeOf(postModel))
doParsing = true
} else if r.Method == http.MethodGet && getModel != nil {
reflectModel = reflect.New(reflect.TypeOf(getModel))
doParsing = true
} else if r.Method == http.MethodDelete && deleteModel != nil {
reflectModel = reflect.New(reflect.TypeOf(deleteModel))
doParsing = true
}
if doParsing {
// Save body
var bodyBytes []byte
if r.Body != nil {
var err error
bodyBytes, err = io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
u.RenderErrorWithStatusCode(w, r, http.StatusInternalServerError, fmt.Errorf("Could not decode request body (%s)", err), false)
u.opts.logParseModelError("parseModelError [path: %s] Could not decode request body %s", r.RequestURI, err.Error())
// execute callback for rawRequestBody also in case of error
handlerOpts.debugRawRequestBody(bodyBytes)
return
}
// execute callback for rawRequestBody
handlerOpts.debugRawRequestBody(bodyBytes)
// restore body for further use
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
// Parse body
modelInterface := reflectModel.Interface()
err := decodeRequestBody(r, modelInterface)
if err != nil {
u.RenderErrorWithStatusCode(w, r, http.StatusBadRequest, fmt.Errorf("Could not decode request body (%s)", err), false)
u.opts.logParseModelError("parseModelError [path: %s] Could not decode request body %s", r.RequestURI, err.Error())
return
}
// Restore body
if r.Body != nil {
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
ctx := context.WithValue(r.Context(), CtxKeyPostModel, modelInterface)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
next.ServeHTTP(w, r)
}
}
}
func parsedModel(r *http.Request) interface{} {
parsedModel := r.Context().Value(CtxKeyPostModel)
return parsedModel
}