1
0
mirror of https://github.com/labstack/echo.git synced 2026-05-16 09:48:24 +02:00

Refactored variable names

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-04-24 10:21:23 -07:00
parent 61fabee05e
commit be825e0229
23 changed files with 300 additions and 303 deletions
+1 -2
View File
@@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 LabStack Copyright (c) 2016 LabStack
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@@ -19,4 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
+12 -12
View File
@@ -452,19 +452,19 @@ func (c *context) Logger() *log.Logger {
} }
func (c *context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error { func (c *context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error {
rq := c.Request() req := c.Request()
rs := c.Response() res := c.Response()
if t, err := time.Parse(http.TimeFormat, rq.Header().Get(HeaderIfModifiedSince)); err == nil && modtime.Before(t.Add(1*time.Second)) { if t, err := time.Parse(http.TimeFormat, req.Header().Get(HeaderIfModifiedSince)); err == nil && modtime.Before(t.Add(1*time.Second)) {
rs.Header().Del(HeaderContentType) res.Header().Del(HeaderContentType)
rs.Header().Del(HeaderContentLength) res.Header().Del(HeaderContentLength)
return c.NoContent(http.StatusNotModified) return c.NoContent(http.StatusNotModified)
} }
rs.Header().Set(HeaderContentType, ContentTypeByExtension(name)) res.Header().Set(HeaderContentType, ContentTypeByExtension(name))
rs.Header().Set(HeaderLastModified, modtime.UTC().Format(http.TimeFormat)) res.Header().Set(HeaderLastModified, modtime.UTC().Format(http.TimeFormat))
rs.WriteHeader(http.StatusOK) res.WriteHeader(http.StatusOK)
_, err := io.Copy(rs, content) _, err := io.Copy(res, content)
return err return err
} }
@@ -478,10 +478,10 @@ func ContentTypeByExtension(name string) (t string) {
return return
} }
func (c *context) Reset(rq engine.Request, rs engine.Response) { func (c *context) Reset(req engine.Request, res engine.Response) {
c.netContext = nil c.netContext = nil
c.request = rq c.request = req
c.response = rs c.response = res
c.store = nil c.store = nil
c.handler = notFoundHandler c.handler = notFoundHandler
} }
+63 -63
View File
@@ -35,9 +35,9 @@ func TestContext(t *testing.T) {
invalidContent := "invalid content" invalidContent := "invalid content"
e := New() e := New()
rq := test.NewRequest(POST, "/", strings.NewReader(userJSON)) req := test.NewRequest(POST, "/", strings.NewReader(userJSON))
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc).(*context) c := e.NewContext(req, rec).(*context)
// Request // Request
assert.NotNil(t, c.Request()) assert.NotNil(t, c.Request())
@@ -89,8 +89,8 @@ func TestContext(t *testing.T) {
c.echo.SetRenderer(tpl) c.echo.SetRenderer(tpl)
err := c.Render(http.StatusOK, "hello", "Joe") err := c.Render(http.StatusOK, "hello", "Joe")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, "Hello, Joe!", rc.Body.String()) assert.Equal(t, "Hello, Joe!", rec.Body.String())
} }
c.echo.renderer = nil c.echo.renderer = nil
@@ -98,102 +98,102 @@ func TestContext(t *testing.T) {
assert.Error(t, err) assert.Error(t, err)
// JSON // JSON
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.JSON(http.StatusOK, user{"1", "Joe"}) err = c.JSON(http.StatusOK, user{"1", "Joe"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, MIMEApplicationJSONCharsetUTF8, rc.Header().Get(HeaderContentType)) assert.Equal(t, MIMEApplicationJSONCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(t, userJSON, rc.Body.String()) assert.Equal(t, userJSON, rec.Body.String())
} }
// JSON (error) // JSON (error)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.JSON(http.StatusOK, make(chan bool)) err = c.JSON(http.StatusOK, make(chan bool))
assert.Error(t, err) assert.Error(t, err)
// JSONP // JSONP
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
callback := "callback" callback := "callback"
err = c.JSONP(http.StatusOK, callback, user{"1", "Joe"}) err = c.JSONP(http.StatusOK, callback, user{"1", "Joe"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, MIMEApplicationJavaScriptCharsetUTF8, rc.Header().Get(HeaderContentType)) assert.Equal(t, MIMEApplicationJavaScriptCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(t, callback+"("+userJSON+");", rc.Body.String()) assert.Equal(t, callback+"("+userJSON+");", rec.Body.String())
} }
// XML // XML
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.XML(http.StatusOK, user{"1", "Joe"}) err = c.XML(http.StatusOK, user{"1", "Joe"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, MIMEApplicationXMLCharsetUTF8, rc.Header().Get(HeaderContentType)) assert.Equal(t, MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(t, xml.Header+userXML, rc.Body.String()) assert.Equal(t, xml.Header+userXML, rec.Body.String())
} }
// XML (error) // XML (error)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.XML(http.StatusOK, make(chan bool)) err = c.XML(http.StatusOK, make(chan bool))
assert.Error(t, err) assert.Error(t, err)
// String // String
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.String(http.StatusOK, "Hello, World!") err = c.String(http.StatusOK, "Hello, World!")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, MIMETextPlainCharsetUTF8, rc.Header().Get(HeaderContentType)) assert.Equal(t, MIMETextPlainCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(t, "Hello, World!", rc.Body.String()) assert.Equal(t, "Hello, World!", rec.Body.String())
} }
// HTML // HTML
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>") err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, MIMETextHTMLCharsetUTF8, rc.Header().Get(HeaderContentType)) assert.Equal(t, MIMETextHTMLCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(t, "Hello, <strong>World!</strong>", rc.Body.String()) assert.Equal(t, "Hello, <strong>World!</strong>", rec.Body.String())
} }
// Attachment // Attachment
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
file, err := os.Open("_fixture/images/walle.png") file, err := os.Open("_fixture/images/walle.png")
if assert.NoError(t, err) { if assert.NoError(t, err) {
err = c.Attachment(file, "walle.png") err = c.Attachment(file, "walle.png")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
assert.Equal(t, "attachment; filename=walle.png", rc.Header().Get(HeaderContentDisposition)) assert.Equal(t, "attachment; filename=walle.png", rec.Header().Get(HeaderContentDisposition))
assert.Equal(t, 219885, rc.Body.Len()) assert.Equal(t, 219885, rec.Body.Len())
} }
} }
// NoContent // NoContent
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
c.NoContent(http.StatusOK) c.NoContent(http.StatusOK)
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
// Redirect // Redirect
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
assert.Equal(t, nil, c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo")) assert.Equal(t, nil, c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo"))
assert.Equal(t, http.StatusMovedPermanently, rc.Status()) assert.Equal(t, http.StatusMovedPermanently, rec.Status())
assert.Equal(t, "http://labstack.github.io/echo", rc.Header().Get(HeaderLocation)) assert.Equal(t, "http://labstack.github.io/echo", rec.Header().Get(HeaderLocation))
// Error // Error
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc).(*context) c = e.NewContext(req, rec).(*context)
c.Error(errors.New("error")) c.Error(errors.New("error"))
assert.Equal(t, http.StatusInternalServerError, rc.Status()) assert.Equal(t, http.StatusInternalServerError, rec.Status())
// Reset // Reset
c.Reset(rq, test.NewResponseRecorder()) c.Reset(req, test.NewResponseRecorder())
} }
func TestContextPath(t *testing.T) { func TestContextPath(t *testing.T) {
@@ -215,9 +215,9 @@ func TestContextQueryParam(t *testing.T) {
q := make(url.Values) q := make(url.Values)
q.Set("name", "joe") q.Set("name", "joe")
q.Set("email", "joe@labstack.com") q.Set("email", "joe@labstack.com")
rq := test.NewRequest(GET, "/?"+q.Encode(), nil) req := test.NewRequest(GET, "/?"+q.Encode(), nil)
e := New() e := New()
c := e.NewContext(rq, nil) c := e.NewContext(req, nil)
assert.Equal(t, "joe", c.QueryParam("name")) assert.Equal(t, "joe", c.QueryParam("name"))
assert.Equal(t, "joe@labstack.com", c.QueryParam("email")) assert.Equal(t, "joe@labstack.com", c.QueryParam("email"))
} }
@@ -228,10 +228,10 @@ func TestContextFormValue(t *testing.T) {
f.Set("email", "joe@labstack.com") f.Set("email", "joe@labstack.com")
e := New() e := New()
rq := test.NewRequest(POST, "/", strings.NewReader(f.Encode())) req := test.NewRequest(POST, "/", strings.NewReader(f.Encode()))
rq.Header().Add(HeaderContentType, MIMEApplicationForm) req.Header().Add(HeaderContentType, MIMEApplicationForm)
c := e.NewContext(rq, nil) c := e.NewContext(req, nil)
assert.Equal(t, "joe", c.FormValue("name")) assert.Equal(t, "joe", c.FormValue("name"))
assert.Equal(t, "joe@labstack.com", c.FormValue("email")) assert.Equal(t, "joe@labstack.com", c.FormValue("email"))
} }
@@ -244,9 +244,9 @@ func TestContextNetContext(t *testing.T) {
func TestContextServeContent(t *testing.T) { func TestContextServeContent(t *testing.T) {
e := New() e := New()
rq := test.NewRequest(GET, "/", nil) req := test.NewRequest(GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
fs := http.Dir("_fixture/images") fs := http.Dir("_fixture/images")
f, err := fs.Open("walle.png") f, err := fs.Open("walle.png")
@@ -255,15 +255,15 @@ func TestContextServeContent(t *testing.T) {
if assert.NoError(t, err) { if assert.NoError(t, err) {
// Not cached // Not cached
if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) { if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) {
assert.Equal(t, http.StatusOK, rc.Status()) assert.Equal(t, http.StatusOK, rec.Status())
} }
// Cached // Cached
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
rq.Header().Set(HeaderIfModifiedSince, fi.ModTime().UTC().Format(http.TimeFormat)) req.Header().Set(HeaderIfModifiedSince, fi.ModTime().UTC().Format(http.TimeFormat))
if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) { if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) {
assert.Equal(t, http.StatusNotModified, rc.Status()) assert.Equal(t, http.StatusNotModified, rec.Status())
} }
} }
} }
+11 -11
View File
@@ -229,10 +229,10 @@ func New() (e *Echo) {
} }
// NewContext returns a Context instance. // NewContext returns a Context instance.
func (e *Echo) NewContext(rq engine.Request, rs engine.Response) Context { func (e *Echo) NewContext(req engine.Request, res engine.Response) Context {
return &context{ return &context{
request: rq, request: req,
response: rs, response: res,
echo: e, echo: e,
pvalues: make([]string, *e.maxParam), pvalues: make([]string, *e.maxParam),
store: make(store), store: make(store),
@@ -520,14 +520,14 @@ func (e *Echo) PutContext(c Context) {
e.pool.Put(c) e.pool.Put(c)
} }
func (e *Echo) ServeHTTP(rq engine.Request, rs engine.Response) { func (e *Echo) ServeHTTP(req engine.Request, res engine.Response) {
c := e.pool.Get().(*context) c := e.pool.Get().(*context)
c.Reset(rq, rs) c.Reset(req, res)
// Middleware // Middleware
h := func(Context) error { h := func(Context) error {
method := rq.Method() method := req.Method()
path := rq.URL().Path() path := req.URL().Path()
e.router.Find(method, path, c) e.router.Find(method, path, c)
h := c.handler h := c.handler
for i := len(e.middleware) - 1; i >= 0; i-- { for i := len(e.middleware) - 1; i >= 0; i-- {
@@ -575,15 +575,15 @@ func (e *HTTPError) Error() string {
} }
func (b *binder) Bind(i interface{}, c Context) (err error) { func (b *binder) Bind(i interface{}, c Context) (err error) {
rq := c.Request() req := c.Request()
ct := rq.Header().Get(HeaderContentType) ct := req.Header().Get(HeaderContentType)
err = ErrUnsupportedMediaType err = ErrUnsupportedMediaType
if strings.HasPrefix(ct, MIMEApplicationJSON) { if strings.HasPrefix(ct, MIMEApplicationJSON) {
if err = json.NewDecoder(rq.Body()).Decode(i); err != nil { if err = json.NewDecoder(req.Body()).Decode(i); err != nil {
err = NewHTTPError(http.StatusBadRequest, err.Error()) err = NewHTTPError(http.StatusBadRequest, err.Error())
} }
} else if strings.HasPrefix(ct, MIMEApplicationXML) { } else if strings.HasPrefix(ct, MIMEApplicationXML) {
if err = xml.NewDecoder(rq.Body()).Decode(i); err != nil { if err = xml.NewDecoder(req.Body()).Decode(i); err != nil {
err = NewHTTPError(http.StatusBadRequest, err.Error()) err = NewHTTPError(http.StatusBadRequest, err.Error())
} }
} }
+10 -10
View File
@@ -24,9 +24,9 @@ type (
func TestEcho(t *testing.T) { func TestEcho(t *testing.T) {
e := New() e := New()
rq := test.NewRequest(GET, "/", nil) req := test.NewRequest(GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
// Router // Router
assert.NotNil(t, e.Router()) assert.NotNil(t, e.Router())
@@ -37,7 +37,7 @@ func TestEcho(t *testing.T) {
// DefaultHTTPErrorHandler // DefaultHTTPErrorHandler
e.DefaultHTTPErrorHandler(errors.New("error"), c) e.DefaultHTTPErrorHandler(errors.New("error"), c)
assert.Equal(t, http.StatusInternalServerError, rc.Status()) assert.Equal(t, http.StatusInternalServerError, rec.Status())
} }
func TestEchoStatic(t *testing.T) { func TestEchoStatic(t *testing.T) {
@@ -289,9 +289,9 @@ func TestEchoGroup(t *testing.T) {
func TestEchoNotFound(t *testing.T) { func TestEchoNotFound(t *testing.T) {
e := New() e := New()
rq := test.NewRequest(GET, "/files", nil) req := test.NewRequest(GET, "/files", nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
e.ServeHTTP(rq, rec) e.ServeHTTP(req, rec)
assert.Equal(t, http.StatusNotFound, rec.Status()) assert.Equal(t, http.StatusNotFound, rec.Status())
} }
@@ -300,9 +300,9 @@ func TestEchoMethodNotAllowed(t *testing.T) {
e.GET("/", func(c Context) error { e.GET("/", func(c Context) error {
return c.String(http.StatusOK, "Echo!") return c.String(http.StatusOK, "Echo!")
}) })
rq := test.NewRequest(POST, "/", nil) req := test.NewRequest(POST, "/", nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
e.ServeHTTP(rq, rec) e.ServeHTTP(req, rec)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Status()) assert.Equal(t, http.StatusMethodNotAllowed, rec.Status())
} }
@@ -328,8 +328,8 @@ func testMethod(t *testing.T, method, path string, e *Echo) {
} }
func request(method, path string, e *Echo) (int, string) { func request(method, path string, e *Echo) (int, string) {
rq := test.NewRequest(method, path, nil) req := test.NewRequest(method, path, nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
e.ServeHTTP(rq, rec) e.ServeHTTP(req, rec)
return rec.Status(), rec.Body.String() return rec.Status(), rec.Body.String()
} }
+2 -2
View File
@@ -170,6 +170,6 @@ type (
) )
// ServeHTTP serves HTTP request. // ServeHTTP serves HTTP request.
func (h HandlerFunc) ServeHTTP(rq Request, rs Response) { func (h HandlerFunc) ServeHTTP(req Request, res Response) {
h(rq, rs) h(req, res)
} }
+27 -27
View File
@@ -78,7 +78,7 @@ func WithConfig(c engine.Config) (s *Server) {
}, },
}, },
}, },
handler: engine.HandlerFunc(func(rq engine.Request, rs engine.Response) { handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
s.logger.Error("handler not set, use `SetHandler()` to set it.") s.logger.Error("handler not set, use `SetHandler()` to set it.")
}), }),
logger: log.New("echo"), logger: log.New("echo"),
@@ -124,38 +124,38 @@ func (s *Server) startCustomListener() error {
func (s *Server) ServeHTTP(c *fasthttp.RequestCtx) { func (s *Server) ServeHTTP(c *fasthttp.RequestCtx) {
// Request // Request
rq := s.pool.request.Get().(*Request) req := s.pool.request.Get().(*Request)
rqHdr := s.pool.requestHeader.Get().(*RequestHeader) reqHdr := s.pool.requestHeader.Get().(*RequestHeader)
rqURL := s.pool.url.Get().(*URL) reqURL := s.pool.url.Get().(*URL)
rqHdr.reset(&c.Request.Header) reqHdr.reset(&c.Request.Header)
rqURL.reset(c.URI()) reqURL.reset(c.URI())
rq.reset(c, rqHdr, rqURL) req.reset(c, reqHdr, reqURL)
// Response // Response
rs := s.pool.response.Get().(*Response) res := s.pool.response.Get().(*Response)
rsHdr := s.pool.responseHeader.Get().(*ResponseHeader) resHdr := s.pool.responseHeader.Get().(*ResponseHeader)
rsHdr.reset(&c.Response.Header) resHdr.reset(&c.Response.Header)
rs.reset(c, rsHdr) res.reset(c, resHdr)
s.handler.ServeHTTP(rq, rs) s.handler.ServeHTTP(req, res)
// Return to pool // Return to pool
s.pool.request.Put(rq) s.pool.request.Put(req)
s.pool.requestHeader.Put(rqHdr) s.pool.requestHeader.Put(reqHdr)
s.pool.url.Put(rqURL) s.pool.url.Put(reqURL)
s.pool.response.Put(rs) s.pool.response.Put(res)
s.pool.responseHeader.Put(rsHdr) s.pool.responseHeader.Put(resHdr)
} }
// WrapHandler wraps `fasthttp.RequestHandler` into `echo.HandlerFunc`. // WrapHandler wraps `fasthttp.RequestHandler` into `echo.HandlerFunc`.
func WrapHandler(h fasthttp.RequestHandler) echo.HandlerFunc { func WrapHandler(h fasthttp.RequestHandler) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request().(*Request) req := c.Request().(*Request)
rs := c.Response().(*Response) res := c.Response().(*Response)
ctx := rq.RequestCtx ctx := req.RequestCtx
h(ctx) h(ctx)
rs.status = ctx.Response.StatusCode() res.status = ctx.Response.StatusCode()
rs.size = int64(ctx.Response.Header.ContentLength()) res.size = int64(ctx.Response.Header.ContentLength())
return nil return nil
} }
} }
@@ -164,12 +164,12 @@ func WrapHandler(h fasthttp.RequestHandler) echo.HandlerFunc {
func WrapMiddleware(h fasthttp.RequestHandler) echo.MiddlewareFunc { func WrapMiddleware(h fasthttp.RequestHandler) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request().(*Request) req := c.Request().(*Request)
rs := c.Response().(*Response) res := c.Response().(*Response)
ctx := rq.RequestCtx ctx := req.RequestCtx
h(ctx) h(ctx)
rs.status = ctx.Response.StatusCode() res.status = ctx.Response.StatusCode()
rs.size = int64(ctx.Response.Header.ContentLength()) res.size = int64(ctx.Response.Header.ContentLength())
return next(c) return next(c)
} }
} }
+2 -2
View File
@@ -134,8 +134,8 @@ func (r *Request) MultipartForm() (*multipart.Form, error) {
return r.Request.MultipartForm, err return r.Request.MultipartForm, err
} }
func (r *Request) reset(rq *http.Request, h engine.Header, u engine.URL) { func (r *Request) reset(req *http.Request, h engine.Header, u engine.URL) {
r.Request = rq r.Request = req
r.header = h r.header = h
r.url = u r.url = u
} }
+25 -25
View File
@@ -76,7 +76,7 @@ func WithConfig(c engine.Config) (s *Server) {
}, },
}, },
}, },
handler: engine.HandlerFunc(func(rq engine.Request, rs engine.Response) { handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
s.logger.Error("handler not set, use `SetHandler()` to set it.") s.logger.Error("handler not set, use `SetHandler()` to set it.")
}), }),
logger: log.New("echo"), logger: log.New("echo"),
@@ -119,37 +119,37 @@ func (s *Server) startCustomListener() error {
// ServeHTTP implements `http.Handler` interface. // ServeHTTP implements `http.Handler` interface.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Request // Request
rq := s.pool.request.Get().(*Request) req := s.pool.request.Get().(*Request)
rqHdr := s.pool.header.Get().(*Header) reqHdr := s.pool.header.Get().(*Header)
rqURL := s.pool.url.Get().(*URL) reqURL := s.pool.url.Get().(*URL)
rqHdr.reset(r.Header) reqHdr.reset(r.Header)
rqURL.reset(r.URL) reqURL.reset(r.URL)
rq.reset(r, rqHdr, rqURL) req.reset(r, reqHdr, reqURL)
// Response // Response
rs := s.pool.response.Get().(*Response) res := s.pool.response.Get().(*Response)
rsAdpt := s.pool.responseAdapter.Get().(*responseAdapter) resAdpt := s.pool.responseAdapter.Get().(*responseAdapter)
rsAdpt.reset(w, rs) resAdpt.reset(w, res)
rsHdr := s.pool.header.Get().(*Header) resHdr := s.pool.header.Get().(*Header)
rsHdr.reset(w.Header()) resHdr.reset(w.Header())
rs.reset(w, rsAdpt, rsHdr) res.reset(w, resAdpt, resHdr)
s.handler.ServeHTTP(rq, rs) s.handler.ServeHTTP(req, res)
// Return to pool // Return to pool
s.pool.request.Put(rq) s.pool.request.Put(req)
s.pool.header.Put(rqHdr) s.pool.header.Put(reqHdr)
s.pool.url.Put(rqURL) s.pool.url.Put(reqURL)
s.pool.response.Put(rs) s.pool.response.Put(res)
s.pool.header.Put(rsHdr) s.pool.header.Put(resHdr)
} }
// WrapHandler wraps `http.Handler` into `echo.HandlerFunc`. // WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
func WrapHandler(h http.Handler) echo.HandlerFunc { func WrapHandler(h http.Handler) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request().(*Request) req := c.Request().(*Request)
rs := c.Response().(*Response) res := c.Response().(*Response)
h.ServeHTTP(rs.ResponseWriter, rq.Request) h.ServeHTTP(res.ResponseWriter, req.Request)
return nil return nil
} }
} }
@@ -158,11 +158,11 @@ func WrapHandler(h http.Handler) echo.HandlerFunc {
func WrapMiddleware(m func(http.Handler) http.Handler) echo.MiddlewareFunc { func WrapMiddleware(m func(http.Handler) http.Handler) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) { return func(c echo.Context) (err error) {
rq := c.Request().(*Request) req := c.Request().(*Request)
rs := c.Response().(*Response) res := c.Response().(*Response)
m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err = next(c) err = next(c)
})).ServeHTTP(rs.ResponseWriter, rq.Request) })).ServeHTTP(res.ResponseWriter, req.Request)
return return
} }
} }
Generated
+5 -5
View File
@@ -1,8 +1,8 @@
hash: 44dfc8aaffca5078e71afdb209a0ef0a359a35f69fb98c7b6a2fb87a5a70e757 hash: 44dfc8aaffca5078e71afdb209a0ef0a359a35f69fb98c7b6a2fb87a5a70e757
updated: 2016-04-20T07:32:00.358585738-07:00 updated: 2016-04-24T10:21:38.007105128-07:00
imports: imports:
- name: github.com/klauspost/compress - name: github.com/klauspost/compress
version: 6ea72a38a8cdbe25966059c547d425e580c624a7 version: 14eb9c4951195779ecfbec34431a976de7335b0a
subpackages: subpackages:
- flate - flate
- gzip - gzip
@@ -12,12 +12,12 @@ imports:
- name: github.com/klauspost/crc32 - name: github.com/klauspost/crc32
version: 19b0b332c9e4516a6370a0456e6182c3b5036720 version: 19b0b332c9e4516a6370a0456e6182c3b5036720
- name: github.com/labstack/gommon - name: github.com/labstack/gommon
version: f8343700e8769e645b5f9949ec2e3a69f9fd71eb version: 4fae226dd67b1100622ab213e798e5ee4c5d4230
subpackages: subpackages:
- color - color
- log - log
- name: github.com/mattn/go-colorable - name: github.com/mattn/go-colorable
version: 9cbef7c35391cca05f15f8181dc0b18bc9736dbb version: bc69d6cebca8dd5675346a34a1c545b67dc74d5e
- name: github.com/mattn/go-isatty - name: github.com/mattn/go-isatty
version: 56b76bdf51f7708750eac80fa38b952bb9f32639 version: 56b76bdf51f7708750eac80fa38b952bb9f32639
- name: github.com/stretchr/testify - name: github.com/stretchr/testify
@@ -29,7 +29,7 @@ imports:
- name: github.com/valyala/fasttemplate - name: github.com/valyala/fasttemplate
version: 3b874956e03f1636d171bda64b130f9135f42cff version: 3b874956e03f1636d171bda64b130f9135f42cff
- name: golang.org/x/net - name: golang.org/x/net
version: fb93926129b8ec0056f2f458b1f519654814edf0 version: b797637b7aeeed133049c7281bfa31dcc9ca42d6
subpackages: subpackages:
- context - context
- websocket - websocket
+10 -10
View File
@@ -12,9 +12,9 @@ import (
func TestBasicAuth(t *testing.T) { func TestBasicAuth(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rs := test.NewResponseRecorder() res := test.NewResponseRecorder()
c := e.NewContext(rq, rs) c := e.NewContext(req, res)
f := func(u, p string) bool { f := func(u, p string) bool {
if u == "joe" && p == "secret" { if u == "joe" && p == "secret" {
return true return true
@@ -27,7 +27,7 @@ func TestBasicAuth(t *testing.T) {
// Valid credentials // Valid credentials
auth := basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret")) auth := basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
rq.Header().Set(echo.HeaderAuthorization, auth) req.Header().Set(echo.HeaderAuthorization, auth)
assert.NoError(t, h(c)) assert.NoError(t, h(c))
//--------------------- //---------------------
@@ -36,21 +36,21 @@ func TestBasicAuth(t *testing.T) {
// Incorrect password // Incorrect password
auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password")) auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
rq.Header().Set(echo.HeaderAuthorization, auth) req.Header().Set(echo.HeaderAuthorization, auth)
he := h(c).(*echo.HTTPError) he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code) assert.Equal(t, http.StatusUnauthorized, he.Code)
assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate)) assert.Equal(t, basic+" realm=Restricted", res.Header().Get(echo.HeaderWWWAuthenticate))
// Empty Authorization header // Empty Authorization header
rq.Header().Set(echo.HeaderAuthorization, "") req.Header().Set(echo.HeaderAuthorization, "")
he = h(c).(*echo.HTTPError) he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code) assert.Equal(t, http.StatusUnauthorized, he.Code)
assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate)) assert.Equal(t, basic+" realm=Restricted", res.Header().Get(echo.HeaderWWWAuthenticate))
// Invalid Authorization header // Invalid Authorization header
auth = base64.StdEncoding.EncodeToString([]byte("invalid")) auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
rq.Header().Set(echo.HeaderAuthorization, auth) req.Header().Set(echo.HeaderAuthorization, auth)
he = h(c).(*echo.HTTPError) he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code) assert.Equal(t, http.StatusUnauthorized, he.Code)
assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate)) assert.Equal(t, basic+" realm=Restricted", res.Header().Get(echo.HeaderWWWAuthenticate))
} }
+9 -9
View File
@@ -52,27 +52,27 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rs := c.Response() res := c.Response()
rs.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding) res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding)
if strings.Contains(c.Request().Header().Get(echo.HeaderAcceptEncoding), scheme) { if strings.Contains(c.Request().Header().Get(echo.HeaderAcceptEncoding), scheme) {
rw := rs.Writer() rw := res.Writer()
gw := pool.Get().(*gzip.Writer) gw := pool.Get().(*gzip.Writer)
gw.Reset(rw) gw.Reset(rw)
defer func() { defer func() {
if rs.Size() == 0 { if res.Size() == 0 {
// We have to reset response to it's pristine state when // We have to reset response to it's pristine state when
// nothing is written to body or error is returned. // nothing is written to body or error is returned.
// See issue #424, #407. // See issue #424, #407.
rs.SetWriter(rw) res.SetWriter(rw)
rs.Header().Del(echo.HeaderContentEncoding) res.Header().Del(echo.HeaderContentEncoding)
gw.Reset(ioutil.Discard) gw.Reset(ioutil.Discard)
} }
gw.Close() gw.Close()
pool.Put(gw) pool.Put(gw)
}() }()
g := gzipResponseWriter{Response: rs, Writer: gw} g := gzipResponseWriter{Response: res, Writer: gw}
rs.Header().Set(echo.HeaderContentEncoding, scheme) res.Header().Set(echo.HeaderContentEncoding, scheme)
rs.SetWriter(g) res.SetWriter(g)
} }
return next(c) return next(c)
} }
+19 -19
View File
@@ -14,9 +14,9 @@ import (
func TestGzip(t *testing.T) { func TestGzip(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
// Skip if no Accept-Encoding header // Skip if no Accept-Encoding header
h := Gzip()(func(c echo.Context) error { h := Gzip()(func(c echo.Context) error {
@@ -24,18 +24,18 @@ func TestGzip(t *testing.T) {
return nil return nil
}) })
h(c) h(c)
assert.Equal(t, "test", rc.Body.String()) assert.Equal(t, "test", rec.Body.String())
rq = test.NewRequest(echo.GET, "/", nil) req = test.NewRequest(echo.GET, "/", nil)
rq.Header().Set(echo.HeaderAcceptEncoding, "gzip") req.Header().Set(echo.HeaderAcceptEncoding, "gzip")
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
// Gzip // Gzip
h(c) h(c)
assert.Equal(t, "gzip", rc.Header().Get(echo.HeaderContentEncoding)) assert.Equal(t, "gzip", rec.Header().Get(echo.HeaderContentEncoding))
assert.Contains(t, rc.Header().Get(echo.HeaderContentType), echo.MIMETextPlain) assert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMETextPlain)
r, err := gzip.NewReader(rc.Body) r, err := gzip.NewReader(rec.Body)
defer r.Close() defer r.Close()
if assert.NoError(t, err) { if assert.NoError(t, err) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
@@ -46,17 +46,17 @@ func TestGzip(t *testing.T) {
func TestGzipNoContent(t *testing.T) { func TestGzipNoContent(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
h := Gzip()(func(c echo.Context) error { h := Gzip()(func(c echo.Context) error {
return c.NoContent(http.StatusOK) return c.NoContent(http.StatusOK)
}) })
h(c) h(c)
assert.Empty(t, rc.Header().Get(echo.HeaderContentEncoding)) assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
assert.Empty(t, rc.Header().Get(echo.HeaderContentType)) assert.Empty(t, rec.Header().Get(echo.HeaderContentType))
b, err := ioutil.ReadAll(rc.Body) b, err := ioutil.ReadAll(rec.Body)
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, 0, len(b)) assert.Equal(t, 0, len(b))
} }
@@ -68,9 +68,9 @@ func TestGzipErrorReturned(t *testing.T) {
e.GET("/", func(c echo.Context) error { e.GET("/", func(c echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, "error") return echo.NewHTTPError(http.StatusInternalServerError, "error")
}) })
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
e.ServeHTTP(rq, rec) e.ServeHTTP(req, rec)
assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding)) assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
b, err := ioutil.ReadAll(rec.Body) b, err := ioutil.ReadAll(rec.Body)
+3 -3
View File
@@ -75,7 +75,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request() req := c.Request()
origin := c.Request().Header().Get(echo.HeaderOrigin) origin := c.Request().Header().Get(echo.HeaderOrigin)
header := c.Response().Header() header := c.Response().Header()
@@ -89,7 +89,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
} }
// Simple request // Simple request
if rq.Method() != echo.OPTIONS { if req.Method() != echo.OPTIONS {
header.Add(echo.HeaderVary, echo.HeaderOrigin) header.Add(echo.HeaderVary, echo.HeaderOrigin)
if origin == "" || allowedOrigin == "" { if origin == "" || allowedOrigin == "" {
return next(c) return next(c)
@@ -119,7 +119,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
if allowHeaders != "" { if allowHeaders != "" {
header.Set(echo.HeaderAccessControlAllowHeaders, allowHeaders) header.Set(echo.HeaderAccessControlAllowHeaders, allowHeaders)
} else { } else {
h := rq.Header().Get(echo.HeaderAccessControlRequestHeaders) h := req.Header().Get(echo.HeaderAccessControlRequestHeaders)
if h != "" { if h != "" {
header.Set(echo.HeaderAccessControlAllowHeaders, h) header.Set(echo.HeaderAccessControlAllowHeaders, h)
} }
+23 -23
View File
@@ -11,9 +11,9 @@ import (
func TestCORS(t *testing.T) { func TestCORS(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
cors := CORSWithConfig(CORSConfig{ cors := CORSWithConfig(CORSConfig{
AllowCredentials: true, AllowCredentials: true,
}) })
@@ -23,21 +23,21 @@ func TestCORS(t *testing.T) {
// No origin header // No origin header
h(c) h(c)
assert.Equal(t, "", rc.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
// Wildcard origin // Wildcard origin
rq = test.NewRequest(echo.GET, "/", nil) req = test.NewRequest(echo.GET, "/", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
rq.Header().Set(echo.HeaderOrigin, "localhost") req.Header().Set(echo.HeaderOrigin, "localhost")
h(c) h(c)
assert.Equal(t, "*", rc.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
// Simple request // Simple request
rq = test.NewRequest(echo.GET, "/", nil) req = test.NewRequest(echo.GET, "/", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
rq.Header().Set(echo.HeaderOrigin, "localhost") req.Header().Set(echo.HeaderOrigin, "localhost")
cors = CORSWithConfig(CORSConfig{ cors = CORSWithConfig(CORSConfig{
AllowOrigins: []string{"localhost"}, AllowOrigins: []string{"localhost"},
AllowCredentials: true, AllowCredentials: true,
@@ -47,17 +47,17 @@ func TestCORS(t *testing.T) {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
}) })
h(c) h(c)
assert.Equal(t, "localhost", rc.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
// Preflight request // Preflight request
rq = test.NewRequest(echo.OPTIONS, "/", nil) req = test.NewRequest(echo.OPTIONS, "/", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
rq.Header().Set(echo.HeaderOrigin, "localhost") req.Header().Set(echo.HeaderOrigin, "localhost")
rq.Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON) req.Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
h(c) h(c)
assert.Equal(t, "localhost", rc.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
assert.NotEmpty(t, rc.Header().Get(echo.HeaderAccessControlAllowMethods)) assert.NotEmpty(t, rec.Header().Get(echo.HeaderAccessControlAllowMethods))
assert.Equal(t, "true", rc.Header().Get(echo.HeaderAccessControlAllowCredentials)) assert.Equal(t, "true", rec.Header().Get(echo.HeaderAccessControlAllowCredentials))
assert.Equal(t, "3600", rc.Header().Get(echo.HeaderAccessControlMaxAge)) assert.Equal(t, "3600", rec.Header().Get(echo.HeaderAccessControlMaxAge))
} }
+15 -16
View File
@@ -84,44 +84,43 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) { return func(c echo.Context) (err error) {
rq := c.Request() req := c.Request()
rs := c.Response() res := c.Response()
start := time.Now() start := time.Now()
if err = next(c); err != nil { if err = next(c); err != nil {
c.Error(err) c.Error(err)
} }
stop := time.Now() stop := time.Now()
buf := config.bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer config.bufferPool.Put(buf)
buffer := config.bufferPool.Get().(*bytes.Buffer) _, err = config.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) {
buffer.Reset()
defer config.bufferPool.Put(buffer)
_, err = config.template.ExecuteFunc(buffer, func(w io.Writer, tag string) (int, error) {
switch tag { switch tag {
case "time_rfc3339": case "time_rfc3339":
return w.Write([]byte(time.Now().Format(time.RFC3339))) return w.Write([]byte(time.Now().Format(time.RFC3339)))
case "remote_ip": case "remote_ip":
ra := rq.RemoteAddress() ra := req.RemoteAddress()
if ip := rq.Header().Get(echo.HeaderXRealIP); ip != "" { if ip := req.Header().Get(echo.HeaderXRealIP); ip != "" {
ra = ip ra = ip
} else if ip = rq.Header().Get(echo.HeaderXForwardedFor); ip != "" { } else if ip = req.Header().Get(echo.HeaderXForwardedFor); ip != "" {
ra = ip ra = ip
} else { } else {
ra, _, _ = net.SplitHostPort(ra) ra, _, _ = net.SplitHostPort(ra)
} }
return w.Write([]byte(ra)) return w.Write([]byte(ra))
case "uri": case "uri":
return w.Write([]byte(rq.URI())) return w.Write([]byte(req.URI()))
case "method": case "method":
return w.Write([]byte(rq.Method())) return w.Write([]byte(req.Method()))
case "path": case "path":
p := rq.URL().Path() p := req.URL().Path()
if p == "" { if p == "" {
p = "/" p = "/"
} }
return w.Write([]byte(p)) return w.Write([]byte(p))
case "status": case "status":
n := rs.Status() n := res.Status()
s := config.color.Green(n) s := config.color.Green(n)
switch { switch {
case n >= 500: case n >= 500:
@@ -135,13 +134,13 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
case "response_time": case "response_time":
return w.Write([]byte(stop.Sub(start).String())) return w.Write([]byte(stop.Sub(start).String()))
case "response_size": case "response_size":
return w.Write([]byte(strconv.FormatInt(rs.Size(), 10))) return w.Write([]byte(strconv.FormatInt(res.Size(), 10)))
default: default:
return w.Write([]byte(fmt.Sprintf("[unknown tag %s]", tag))) return w.Write([]byte(fmt.Sprintf("[unknown tag %s]", tag)))
} }
}) })
if err == nil { if err == nil {
config.Output.Write(buffer.Bytes()) config.Output.Write(buf.Bytes())
} }
return return
} }
+16 -17
View File
@@ -14,9 +14,9 @@ import (
func TestLogger(t *testing.T) { func TestLogger(t *testing.T) {
// Note: Just for the test coverage, not a real test. // Note: Just for the test coverage, not a real test.
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
h := Logger()(func(c echo.Context) error { h := Logger()(func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
}) })
@@ -25,25 +25,25 @@ func TestLogger(t *testing.T) {
h(c) h(c)
// Status 3xx // Status 3xx
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error { h = Logger()(func(c echo.Context) error {
return c.String(http.StatusTemporaryRedirect, "test") return c.String(http.StatusTemporaryRedirect, "test")
}) })
h(c) h(c)
// Status 4xx // Status 4xx
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error { h = Logger()(func(c echo.Context) error {
return c.String(http.StatusNotFound, "test") return c.String(http.StatusNotFound, "test")
}) })
h(c) h(c)
// Status 5xx with empty path // Status 5xx with empty path
rq = test.NewRequest(echo.GET, "", nil) req = test.NewRequest(echo.GET, "", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error { h = Logger()(func(c echo.Context) error {
return errors.New("error") return errors.New("error")
}) })
@@ -52,9 +52,9 @@ func TestLogger(t *testing.T) {
func TestLoggerIPAddress(t *testing.T) { func TestLoggerIPAddress(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
e.Logger().SetOutput(buf) e.Logger().SetOutput(buf)
ip := "127.0.0.1" ip := "127.0.0.1"
@@ -63,18 +63,17 @@ func TestLoggerIPAddress(t *testing.T) {
}) })
// With X-Real-IP // With X-Real-IP
rq.Header().Add(echo.HeaderXRealIP, ip) req.Header().Add(echo.HeaderXRealIP, ip)
h(c) h(c)
assert.Contains(t, ip, buf.String()) assert.Contains(t, ip, buf.String())
// With X-Forwarded-For // With X-Forwarded-For
buf.Reset() buf.Reset()
rq.Header().Del(echo.HeaderXRealIP) req.Header().Del(echo.HeaderXRealIP)
rq.Header().Add(echo.HeaderXForwardedFor, ip) req.Header().Add(echo.HeaderXForwardedFor, ip)
h(c) h(c)
assert.Contains(t, ip, buf.String()) assert.Contains(t, ip, buf.String())
// with rq.RemoteAddr
buf.Reset() buf.Reset()
h(c) h(c)
assert.Contains(t, ip, buf.String()) assert.Contains(t, ip, buf.String())
+4 -4
View File
@@ -14,13 +14,13 @@ func TestRecover(t *testing.T) {
e := echo.New() e := echo.New()
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
e.SetLogOutput(buf) e.SetLogOutput(buf)
rq := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
h := Recover()(echo.HandlerFunc(func(c echo.Context) error { h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
panic("test") panic("test")
})) }))
h(c) h(c)
assert.Equal(t, http.StatusInternalServerError, rc.Status()) assert.Equal(t, http.StatusInternalServerError, rec.Status())
assert.Contains(t, buf.String(), "PANIC RECOVER") assert.Contains(t, buf.String(), "PANIC RECOVER")
} }
+6 -6
View File
@@ -26,8 +26,8 @@ func AddTrailingSlash() echo.MiddlewareFunc {
func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc { func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request() req := c.Request()
url := rq.URL() url := req.URL()
path := url.Path() path := url.Path()
qs := url.QueryString() qs := url.QueryString()
if path != "/" && path[len(path)-1] != '/' { if path != "/" && path[len(path)-1] != '/' {
@@ -39,7 +39,7 @@ func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc
if config.RedirectCode != 0 { if config.RedirectCode != 0 {
return c.Redirect(config.RedirectCode, uri) return c.Redirect(config.RedirectCode, uri)
} }
rq.SetURI(uri) req.SetURI(uri)
url.SetPath(path) url.SetPath(path)
} }
return next(c) return next(c)
@@ -60,8 +60,8 @@ func RemoveTrailingSlash() echo.MiddlewareFunc {
func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc { func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
rq := c.Request() req := c.Request()
url := rq.URL() url := req.URL()
path := url.Path() path := url.Path()
qs := url.QueryString() qs := url.QueryString()
l := len(path) - 1 l := len(path) - 1
@@ -74,7 +74,7 @@ func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFu
if config.RedirectCode != 0 { if config.RedirectCode != 0 {
return c.Redirect(config.RedirectCode, uri) return c.Redirect(config.RedirectCode, uri)
} }
rq.SetURI(uri) req.SetURI(uri)
url.SetPath(path) url.SetPath(path)
} }
return next(c) return next(c)
+20 -20
View File
@@ -11,52 +11,52 @@ import (
func TestAddTrailingSlash(t *testing.T) { func TestAddTrailingSlash(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/add-slash", nil) req := test.NewRequest(echo.GET, "/add-slash", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
h := AddTrailingSlash()(func(c echo.Context) error { h := AddTrailingSlash()(func(c echo.Context) error {
return nil return nil
}) })
h(c) h(c)
assert.Equal(t, "/add-slash/", rq.URL().Path()) assert.Equal(t, "/add-slash/", req.URL().Path())
assert.Equal(t, "/add-slash/", rq.URI()) assert.Equal(t, "/add-slash/", req.URI())
// With config // With config
rq = test.NewRequest(echo.GET, "/add-slash?key=value", nil) req = test.NewRequest(echo.GET, "/add-slash?key=value", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
h = AddTrailingSlashWithConfig(TrailingSlashConfig{ h = AddTrailingSlashWithConfig(TrailingSlashConfig{
RedirectCode: http.StatusMovedPermanently, RedirectCode: http.StatusMovedPermanently,
})(func(c echo.Context) error { })(func(c echo.Context) error {
return nil return nil
}) })
h(c) h(c)
assert.Equal(t, http.StatusMovedPermanently, rc.Status()) assert.Equal(t, http.StatusMovedPermanently, rec.Status())
assert.Equal(t, "/add-slash/?key=value", rc.Header().Get(echo.HeaderLocation)) assert.Equal(t, "/add-slash/?key=value", rec.Header().Get(echo.HeaderLocation))
} }
func TestRemoveTrailingSlash(t *testing.T) { func TestRemoveTrailingSlash(t *testing.T) {
e := echo.New() e := echo.New()
rq := test.NewRequest(echo.GET, "/remove-slash/", nil) req := test.NewRequest(echo.GET, "/remove-slash/", nil)
rc := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := e.NewContext(rq, rc) c := e.NewContext(req, rec)
h := RemoveTrailingSlash()(func(c echo.Context) error { h := RemoveTrailingSlash()(func(c echo.Context) error {
return nil return nil
}) })
h(c) h(c)
assert.Equal(t, "/remove-slash", rq.URL().Path()) assert.Equal(t, "/remove-slash", req.URL().Path())
assert.Equal(t, "/remove-slash", rq.URI()) assert.Equal(t, "/remove-slash", req.URI())
// With config // With config
rq = test.NewRequest(echo.GET, "/remove-slash/?key=value", nil) req = test.NewRequest(echo.GET, "/remove-slash/?key=value", nil)
rc = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = e.NewContext(rq, rc) c = e.NewContext(req, rec)
h = RemoveTrailingSlashWithConfig(TrailingSlashConfig{ h = RemoveTrailingSlashWithConfig(TrailingSlashConfig{
RedirectCode: http.StatusMovedPermanently, RedirectCode: http.StatusMovedPermanently,
})(func(c echo.Context) error { })(func(c echo.Context) error {
return nil return nil
}) })
h(c) h(c)
assert.Equal(t, http.StatusMovedPermanently, rc.Status()) assert.Equal(t, http.StatusMovedPermanently, rec.Status())
assert.Equal(t, "/remove-slash?key=value", rc.Header().Get(echo.HeaderLocation)) assert.Equal(t, "/remove-slash?key=value", rec.Header().Get(echo.HeaderLocation))
} }
+5 -5
View File
@@ -87,9 +87,9 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
} }
// Create a directory index // Create a directory index
rs := c.Response() res := c.Response()
rs.Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8) res.Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8)
if _, err = fmt.Fprintf(rs, "<pre>\n"); err != nil { if _, err = fmt.Fprintf(res, "<pre>\n"); err != nil {
return err return err
} }
for _, d := range dirs { for _, d := range dirs {
@@ -99,11 +99,11 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
color = "#e91e63" color = "#e91e63"
name += "/" name += "/"
} }
if _, err = fmt.Fprintf(rs, "<a href=\"%s\" style=\"color: %s;\">%s</a>\n", name, color, name); err != nil { if _, err = fmt.Fprintf(res, "<a href=\"%s\" style=\"color: %s;\">%s</a>\n", name, color, name); err != nil {
return err return err
} }
} }
_, err = fmt.Fprintf(rs, "</pre>\n") _, err = fmt.Fprintf(res, "</pre>\n")
return err return err
} }
if fi, err = f.Stat(); err != nil { // Index file if fi, err = f.Stat(); err != nil { // Index file
+2 -2
View File
@@ -112,8 +112,8 @@ func (r *Request) MultipartForm() (*multipart.Form, error) {
return r.request.MultipartForm, err return r.request.MultipartForm, err
} }
func (r *Request) reset(rq *http.Request, h engine.Header, u engine.URL) { func (r *Request) reset(req *http.Request, h engine.Header, u engine.URL) {
r.request = rq r.request = req
r.header = h r.header = h
r.url = u r.url = u
} }
+8 -8
View File
@@ -65,7 +65,7 @@ func NewConfig(c *engine.Config) (s *Server) {
}, },
}, },
}, },
handler: engine.HandlerFunc(func(rq engine.Request, rs engine.Response) { handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
s.logger.Fatal("handler not set") s.logger.Fatal("handler not set")
}), }),
logger: log.New("echo"), logger: log.New("echo"),
@@ -95,24 +95,24 @@ func (s *Server) Start() {
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Request // Request
rq := s.pool.request.Get().(*Request) req := s.pool.request.Get().(*Request)
reqHdr := s.pool.header.Get().(*Header) reqHdr := s.pool.header.Get().(*Header)
reqURL := s.pool.url.Get().(*URL) reqURL := s.pool.url.Get().(*URL)
reqHdr.reset(r.Header) reqHdr.reset(r.Header)
reqURL.reset(r.URL) reqURL.reset(r.URL)
rq.reset(r, reqHdr, reqURL) req.reset(r, reqHdr, reqURL)
// Response // Response
rs := s.pool.response.Get().(*Response) res := s.pool.response.Get().(*Response)
resHdr := s.pool.header.Get().(*Header) resHdr := s.pool.header.Get().(*Header)
resHdr.reset(w.Header()) resHdr.reset(w.Header())
rs.reset(w, resHdr) res.reset(w, resHdr)
s.handler.ServeHTTP(rq, rs) s.handler.ServeHTTP(req, res)
s.pool.request.Put(rq) s.pool.request.Put(req)
s.pool.header.Put(reqHdr) s.pool.header.Put(reqHdr)
s.pool.url.Put(reqURL) s.pool.url.Put(reqURL)
s.pool.response.Put(rs) s.pool.response.Put(res)
s.pool.header.Put(resHdr) s.pool.header.Put(resHdr)
} }