forked from zerodha/fastglue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom.go
207 lines (171 loc) · 5.89 KB
/
custom.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
package fastglue
import (
"encoding/json"
"fmt"
fasthttprouter "github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
const (
statusSuccess = "success"
statusError = "error"
excepBadRequest = "InputException"
excepGeneral = "GeneralException"
)
// ErrorType defines string error constants (eg: TokenException)
// to be sent with JSON responses.
type ErrorType string
// Envelope is a highly opinionated, "standardised", JSON response
// structure.
type Envelope struct {
Status string `json:"status"`
Message *string `json:"message,omitempty"`
Data interface{} `json:"data"`
ErrorType *ErrorType `json:"error_type,omitempty"`
}
// NewGlue creates and returns a new instance of Fastglue with custom error
// handlers pre-bound.
func NewGlue() *Fastglue {
f := New()
f.Router.MethodNotAllowed = BadMethodHandler
f.Router.NotFound = NotFoundHandler
f.Router.SaveMatchedRoutePath = true
f.MatchedRoutePathParam = fasthttprouter.MatchedRoutePathParam
return f
}
// DecodeFail uses Decode() to unmarshal the Post body, but in addition to returning
// an error on failure, writes the error to the HTTP response directly. This helps
// avoid repeating read/parse/validate boilerplate inside every single HTTP handler.
func (r *Request) DecodeFail(v interface{}, tag string) error {
if err := r.Decode(v, tag); err != nil {
if errSend := r.SendErrorEnvelope(fasthttp.StatusBadRequest,
"Error unmarshalling request: `"+err.Error()+"`", nil, excepBadRequest); errSend != nil {
return errSend
}
return err
}
return nil
}
// SendEnvelope is a highly opinionated method that sends success responses in a predefined
// structure which has become customary at Rainmatter internally.
func (r *Request) SendEnvelope(data interface{}) error {
// If data is json.RawMessage, we're getting a pre-formatted JSON byte array.
// Skip the marshaller, fake the envelope and send it right away.
if j, ok := data.(json.RawMessage); ok {
r.RequestCtx.SetStatusCode(fasthttp.StatusOK)
r.RequestCtx.SetContentType(JSON)
if _, err := r.RequestCtx.Write([]byte(`{"status": "` + statusSuccess + `", "data": `)); err != nil {
return err
}
if _, err := r.RequestCtx.Write(j); err != nil {
return err
}
if _, err := r.RequestCtx.Write([]byte(`}`)); err != nil {
return err
}
return nil
}
// Standard marshalled envelope.
e := Envelope{
Status: statusSuccess,
Data: data,
}
if err := r.SendJSON(fasthttp.StatusOK, e); err != nil {
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, "Couldn't marshal JSON: `"+err.Error()+"`", nil, excepGeneral)
}
return nil
}
// SendErrorEnvelope is a highly opinionated method that sends error responses in a predefined
// structure which has become customary at Rainmatter internally.
func (r *Request) SendErrorEnvelope(code int, message string, data interface{}, et ErrorType) error {
var e Envelope
if et == "" {
e = Envelope{
Status: statusError,
Message: &message,
Data: data,
}
} else {
e = Envelope{
Status: statusError,
Message: &message,
Data: data,
ErrorType: &et,
}
}
return r.SendJSON(code, e)
}
// ReqParams is an (opinionated) middleware that checks if a given set of parameters are set in
// the GET or POST params. If not, it fails the request with an error envelope.
func ReqParams(h FastRequestHandler, fields []string) FastRequestHandler {
return func(r *Request) error {
var args *fasthttp.Args
if r.RequestCtx.IsPost() || r.RequestCtx.IsPut() {
args = r.RequestCtx.PostArgs()
} else {
args = r.RequestCtx.QueryArgs()
}
for _, f := range fields {
if !args.Has(f) || len(args.Peek(f)) == 0 {
_ = r.SendErrorEnvelope(fasthttp.StatusBadRequest, "Missing or empty field `"+f+"`", nil, excepBadRequest)
return nil
}
}
return h(r)
}
}
// ReqLenParams is an (opinionated) middleware that checks if a given set of parameters are set in
// the GET or POST params and if each of them meets a minimum length criteria.
// If not, it fails the request with an error envelop.
func ReqLenParams(h FastRequestHandler, fields map[string]int) FastRequestHandler {
return func(r *Request) error {
var args *fasthttp.Args
if r.RequestCtx.IsPost() || r.RequestCtx.IsPut() {
args = r.RequestCtx.PostArgs()
} else {
args = r.RequestCtx.QueryArgs()
}
for f, ln := range fields {
if !args.Has(f) || len(args.Peek(f)) < ln {
_ = r.SendErrorEnvelope(fasthttp.StatusBadRequest,
fmt.Sprintf("`%s` should be minimum %d characters in length.", f, ln), nil, excepBadRequest)
return nil
}
}
return h(r)
}
}
// ReqLenRangeParams is an (opinionated) middleware that checks if a given set of parameters are set in
// the GET or POST params and if each of them meets a minimum and maximum length range criteria.
// If not, it fails the request with an error envelop.
func ReqLenRangeParams(h FastRequestHandler, fields map[string][2]int) FastRequestHandler {
return func(r *Request) error {
var args *fasthttp.Args
if r.RequestCtx.IsPost() || r.RequestCtx.IsPut() {
args = r.RequestCtx.PostArgs()
} else {
args = r.RequestCtx.QueryArgs()
}
for f, ln := range fields {
if !args.Has(f) || len(args.Peek(f)) < ln[0] || len(args.Peek(f)) > ln[1] {
_ = r.SendErrorEnvelope(fasthttp.StatusBadRequest,
fmt.Sprintf("`%s` should be %d to %d in length", f, ln[0], ln[1]), nil, excepBadRequest)
return nil
}
}
return h(r)
}
}
// NotFoundHandler produces an enveloped JSON response for 404 errors.
func NotFoundHandler(r *fasthttp.RequestCtx) {
req := &Request{
RequestCtx: r,
}
_ = req.SendErrorEnvelope(fasthttp.StatusNotFound, "Route not found", nil, excepGeneral)
}
// BadMethodHandler produces an enveloped JSON response for 405 errors.
func BadMethodHandler(r *fasthttp.RequestCtx) {
req := &Request{
RequestCtx: r,
}
_ = req.SendErrorEnvelope(fasthttp.StatusMethodNotAllowed, "Request method not allowed", nil, excepGeneral)
}