forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo.go
468 lines (394 loc) · 10.6 KB
/
echo.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
package echo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"runtime"
"strings"
"sync"
"encoding/xml"
"github.com/labstack/echo/engine"
"github.com/labstack/echo/logger"
"github.com/labstack/gommon/log"
)
type (
Echo struct {
prefix string
middleware []Middleware
head Handler
maxParam *int
notFoundHandler HandlerFunc
httpErrorHandler HTTPErrorHandler
binder Binder
renderer Renderer
pool sync.Pool
debug bool
router *Router
logger logger.Logger
}
Route struct {
Method string
Path string
Handler string
}
HTTPError struct {
code int
message string
}
Middleware interface {
Handle(Handler) Handler
}
MiddlewareFunc func(Handler) Handler
Handler interface {
Handle(Context) error
}
HandlerFunc func(Context) error
// HTTPErrorHandler is a centralized HTTP error handler.
HTTPErrorHandler func(error, Context)
// Binder is the interface that wraps the Bind method.
Binder interface {
Bind(engine.Request, interface{}) error
}
binder struct {
}
// Validator is the interface that wraps the Validate method.
Validator interface {
Validate() error
}
// Renderer is the interface that wraps the Render method.
Renderer interface {
Render(w io.Writer, name string, data interface{}) error
}
)
const (
// CONNECT HTTP method
CONNECT = "CONNECT"
// DELETE HTTP method
DELETE = "DELETE"
// GET HTTP method
GET = "GET"
// HEAD HTTP method
HEAD = "HEAD"
// OPTIONS HTTP method
OPTIONS = "OPTIONS"
// PATCH HTTP method
PATCH = "PATCH"
// POST HTTP method
POST = "POST"
// PUT HTTP method
PUT = "PUT"
// TRACE HTTP method
TRACE = "TRACE"
//-------------
// Media types
//-------------
ApplicationJSON = "application/json"
ApplicationJSONCharsetUTF8 = ApplicationJSON + "; " + CharsetUTF8
ApplicationJavaScript = "application/javascript"
ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
ApplicationXML = "application/xml"
ApplicationXMLCharsetUTF8 = ApplicationXML + "; " + CharsetUTF8
ApplicationForm = "application/x-www-form-urlencoded"
ApplicationProtobuf = "application/protobuf"
ApplicationMsgpack = "application/msgpack"
TextHTML = "text/html"
TextHTMLCharsetUTF8 = TextHTML + "; " + CharsetUTF8
TextPlain = "text/plain"
TextPlainCharsetUTF8 = TextPlain + "; " + CharsetUTF8
MultipartForm = "multipart/form-data"
OctetStream = "application/octet-stream"
//---------
// Charset
//---------
CharsetUTF8 = "charset=utf-8"
//---------
// Headers
//---------
AcceptEncoding = "Accept-Encoding"
Authorization = "Authorization"
ContentDisposition = "Content-Disposition"
ContentEncoding = "Content-Encoding"
ContentLength = "Content-Length"
ContentType = "Content-Type"
Location = "Location"
Upgrade = "Upgrade"
Vary = "Vary"
WWWAuthenticate = "WWW-Authenticate"
XForwardedFor = "X-Forwarded-For"
XRealIP = "X-Real-IP"
//-----------
// Protocols
//-----------
WebSocket = "websocket"
)
var (
methods = [...]string{
CONNECT,
DELETE,
GET,
HEAD,
OPTIONS,
PATCH,
POST,
PUT,
TRACE,
}
//--------
// Errors
//--------
ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
ErrNotFound = NewHTTPError(http.StatusNotFound)
ErrRendererNotRegistered = errors.New("renderer not registered")
ErrInvalidRedirectCode = errors.New("invalid redirect status code")
//----------------
// Error handlers
//----------------
notFoundHandler = HandlerFunc(func(c Context) error {
return NewHTTPError(http.StatusNotFound)
})
methodNotAllowedHandler = HandlerFunc(func(c Context) error {
return NewHTTPError(http.StatusMethodNotAllowed)
})
)
// New creates an instance of Echo.
func New() (e *Echo) {
e = &Echo{maxParam: new(int)}
e.pool.New = func() interface{} {
// NOTE: v2
return NewContext(nil, nil, e)
}
e.router = NewRouter(e)
e.head = e.router.Handle(nil)
//----------
// Defaults
//----------
e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
e.SetBinder(&binder{})
// Logger
e.logger = log.New("echo")
return
}
func (m MiddlewareFunc) Handle(h Handler) Handler {
return m(h)
}
func (h HandlerFunc) Handle(c Context) error {
return h(c)
}
// Router returns router.
func (e *Echo) Router() *Router {
return e.router
}
// SetLogger sets the logger instance.
func (e *Echo) SetLogger(l logger.Logger) {
e.logger = l
}
// Logger returns the logger instance.
func (e *Echo) Logger() logger.Logger {
return e.logger
}
// DefaultHTTPErrorHandler invokes the default HTTP error handler.
func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
code := http.StatusInternalServerError
msg := http.StatusText(code)
if he, ok := err.(*HTTPError); ok {
code = he.code
msg = he.message
}
if e.debug {
msg = err.Error()
}
if !c.Response().Committed() {
c.String(code, msg)
}
e.logger.Error(err)
}
// SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.
func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler) {
e.httpErrorHandler = h
}
// SetBinder registers a custom binder. It's invoked by Context.Bind().
func (e *Echo) SetBinder(b Binder) {
e.binder = b
}
// SetRenderer registers an HTML template renderer. It's invoked by Context.Render().
func (e *Echo) SetRenderer(r Renderer) {
e.renderer = r
}
// SetDebug enable/disable debug mode.
func (e *Echo) SetDebug(on bool) {
e.debug = on
}
// Debug returns debug mode (enabled or disabled).
func (e *Echo) Debug() bool {
return e.debug
}
// Use adds handler to the middleware chain.
func (e *Echo) Use(middleware ...Middleware) {
e.middleware = append(e.middleware, middleware...)
m := append(e.middleware, e.router)
// Chain middleware
for i := len(m) - 1; i >= 0; i-- {
e.head = m[i].Handle(e.head)
}
}
// Connect adds a CONNECT route > handler to the router.
func (e *Echo) Connect(path string, h Handler, m ...Middleware) {
e.add(CONNECT, path, h, m...)
}
// Delete adds a DELETE route > handler to the router.
func (e *Echo) Delete(path string, h Handler, m ...Middleware) {
e.add(DELETE, path, h, m...)
}
// Get adds a GET route > handler to the router.
func (e *Echo) Get(path string, h Handler, m ...Middleware) {
e.add(GET, path, h, m...)
}
// Head adds a HEAD route > handler to the router.
func (e *Echo) Head(path string, h Handler, m ...Middleware) {
e.add(HEAD, path, h, m...)
}
// Options adds an OPTIONS route > handler to the router.
func (e *Echo) Options(path string, h Handler, m ...Middleware) {
e.add(OPTIONS, path, h, m...)
}
// Patch adds a PATCH route > handler to the router.
func (e *Echo) Patch(path string, h Handler, m ...Middleware) {
e.add(PATCH, path, h, m...)
}
// Post adds a POST route > handler to the router.
func (e *Echo) Post(path string, h Handler, m ...Middleware) {
e.add(POST, path, h, m...)
}
// Put adds a PUT route > handler to the router.
func (e *Echo) Put(path string, h Handler, m ...Middleware) {
e.add(PUT, path, h, m...)
}
// Trace adds a TRACE route > handler to the router.
func (e *Echo) Trace(path string, h Handler, m ...Middleware) {
e.add(TRACE, path, h, m...)
}
// Any adds a route > handler to the router for all HTTP methods.
func (e *Echo) Any(path string, handler Handler, middleware ...Middleware) {
for _, m := range methods {
e.add(m, path, handler, middleware...)
}
}
// Match adds a route > handler to the router for multiple HTTP methods provided.
func (e *Echo) Match(methods []string, path string, handler Handler, middleware ...Middleware) {
for _, m := range methods {
e.add(m, path, handler, middleware...)
}
}
func (e *Echo) add(method, path string, handler Handler, middleware ...Middleware) {
name := handlerName(handler)
e.router.Add(method, path, HandlerFunc(func(c Context) error {
for _, m := range middleware {
handler = m.Handle(handler)
}
return handler.Handle(c)
}), e)
r := Route{
Method: method,
Path: path,
Handler: name,
}
e.router.routes = append(e.router.routes, r)
}
// Group creates a new sub-router with prefix.
func (e *Echo) Group(prefix string, m ...Middleware) (g *Group) {
g = &Group{prefix: prefix, echo: e}
g.Use(m...)
return
}
// URI generates a URI from handler.
func (e *Echo) URI(handler Handler, params ...interface{}) string {
uri := new(bytes.Buffer)
ln := len(params)
n := 0
name := handlerName(handler)
for _, r := range e.router.routes {
if r.Handler == name {
for i, l := 0, len(r.Path); i < l; i++ {
if r.Path[i] == ':' && n < ln {
for ; i < l && r.Path[i] != '/'; i++ {
}
uri.WriteString(fmt.Sprintf("%v", params[n]))
n++
}
if i < l {
uri.WriteByte(r.Path[i])
}
}
break
}
}
return uri.String()
}
// URL is an alias for `URI` function.
func (e *Echo) URL(h Handler, params ...interface{}) string {
return e.URI(h, params...)
}
// Routes returns the registered routes.
func (e *Echo) Routes() []Route {
return e.router.routes
}
func (e *Echo) ServeHTTP(req engine.Request, res engine.Response) {
c := e.pool.Get().(*context)
c.reset(req, res)
// Execute chain
if err := e.head.Handle(c); err != nil {
e.httpErrorHandler(err, c)
}
e.pool.Put(c)
}
// Run starts the HTTP engine.
func (e *Echo) Run(eng engine.Engine) {
eng.SetHandler(e.ServeHTTP)
eng.SetLogger(e.logger)
eng.Start()
}
func NewHTTPError(code int, msg ...string) *HTTPError {
he := &HTTPError{code: code, message: http.StatusText(code)}
if len(msg) > 0 {
m := msg[0]
he.message = m
}
return he
}
// SetCode sets code.
func (e *HTTPError) SetCode(code int) {
e.code = code
}
// Code returns code.
func (e *HTTPError) Code() int {
return e.code
}
// Error returns message.
func (e *HTTPError) Error() string {
return e.message
}
func (binder) Bind(r engine.Request, i interface{}) (err error) {
ct := r.Header().Get(ContentType)
err = ErrUnsupportedMediaType
if strings.HasPrefix(ct, ApplicationJSON) {
if err = json.NewDecoder(r.Body()).Decode(i); err != nil {
err = NewHTTPError(http.StatusBadRequest, err.Error())
}
} else if strings.HasPrefix(ct, ApplicationXML) {
if err = xml.NewDecoder(r.Body()).Decode(i); err != nil {
err = NewHTTPError(http.StatusBadRequest, err.Error())
}
}
return
}
func handlerName(h Handler) string {
t := reflect.ValueOf(h).Type()
if t.Kind() == reflect.Func {
return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
}
return t.String()
}