1
0
mirror of https://github.com/labstack/echo.git synced 2025-06-15 00:14:57 +02:00

Replace http constants with stdlib ones, i.e.: http.MethodGet instead of echo.GET (#1205)

This commit is contained in:
Emir Ribić
2018-10-14 17:16:58 +02:00
committed by Vishal Rana
parent 059c099762
commit c8fd197fa8
33 changed files with 270 additions and 271 deletions

View File

@ -31,7 +31,7 @@ type (
func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) { func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) {
req := c.Request() req := c.Request()
if req.ContentLength == 0 { if req.ContentLength == 0 {
if req.Method == GET || req.Method == DELETE { if req.Method == http.MethodGet || req.Method == http.MethodDelete {
if err = b.bindData(i, c.QueryParams(), "query"); err != nil { if err = b.bindData(i, c.QueryParams(), "query"); err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
} }

View File

@ -145,7 +145,7 @@ func TestBindForm(t *testing.T) {
testBindOkay(assert, strings.NewReader(userForm), MIMEApplicationForm) testBindOkay(assert, strings.NewReader(userForm), MIMEApplicationForm)
testBindError(assert, nil, MIMEApplicationForm, nil) testBindError(assert, nil, MIMEApplicationForm, nil)
e := New() e := New()
req := httptest.NewRequest(POST, "/", strings.NewReader(userForm)) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userForm))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
req.Header.Set(HeaderContentType, MIMEApplicationForm) req.Header.Set(HeaderContentType, MIMEApplicationForm)
@ -155,7 +155,7 @@ func TestBindForm(t *testing.T) {
func TestBindQueryParams(t *testing.T) { func TestBindQueryParams(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/?id=1&name=Jon+Snow", nil) req := httptest.NewRequest(http.MethodGet, "/?id=1&name=Jon+Snow", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
u := new(user) u := new(user)
@ -168,7 +168,7 @@ func TestBindQueryParams(t *testing.T) {
func TestBindQueryParamsCaseInsensitive(t *testing.T) { func TestBindQueryParamsCaseInsensitive(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/?ID=1&NAME=Jon+Snow", nil) req := httptest.NewRequest(http.MethodGet, "/?ID=1&NAME=Jon+Snow", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
u := new(user) u := new(user)
@ -181,7 +181,7 @@ func TestBindQueryParamsCaseInsensitive(t *testing.T) {
func TestBindQueryParamsCaseSensitivePrioritized(t *testing.T) { func TestBindQueryParamsCaseSensitivePrioritized(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/?id=1&ID=2&NAME=Jon+Snow&name=Jon+Doe", nil) req := httptest.NewRequest(http.MethodGet, "/?id=1&ID=2&NAME=Jon+Snow&name=Jon+Doe", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
u := new(user) u := new(user)
@ -194,7 +194,7 @@ func TestBindQueryParamsCaseSensitivePrioritized(t *testing.T) {
func TestBindUnmarshalParam(t *testing.T) { func TestBindUnmarshalParam(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/?ts=2016-12-06T19:09:05Z&sa=one,two,three&ta=2016-12-06T19:09:05Z&ta=2016-12-06T19:09:05Z&ST=baz", nil) req := httptest.NewRequest(http.MethodGet, "/?ts=2016-12-06T19:09:05Z&sa=one,two,three&ta=2016-12-06T19:09:05Z&ta=2016-12-06T19:09:05Z&ST=baz", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
result := struct { result := struct {
@ -218,7 +218,7 @@ func TestBindUnmarshalParam(t *testing.T) {
func TestBindUnmarshalParamPtr(t *testing.T) { func TestBindUnmarshalParamPtr(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/?ts=2016-12-06T19:09:05Z", nil) req := httptest.NewRequest(http.MethodGet, "/?ts=2016-12-06T19:09:05Z", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
result := struct { result := struct {
@ -257,7 +257,7 @@ func TestBindbindData(t *testing.T) {
func TestBindUnmarshalTypeError(t *testing.T) { func TestBindUnmarshalTypeError(t *testing.T) {
body := bytes.NewBufferString(`{ "id": "text" }`) body := bytes.NewBufferString(`{ "id": "text" }`)
e := New() e := New()
req := httptest.NewRequest(POST, "/", body) req := httptest.NewRequest(http.MethodPost, "/", body)
req.Header.Set(HeaderContentType, MIMEApplicationJSON) req.Header.Set(HeaderContentType, MIMEApplicationJSON)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
@ -364,7 +364,7 @@ func assertBindTestStruct(a *assert.Assertions, ts *bindTestStruct) {
func testBindOkay(assert *assert.Assertions, r io.Reader, ctype string) { func testBindOkay(assert *assert.Assertions, r io.Reader, ctype string) {
e := New() e := New()
req := httptest.NewRequest(POST, "/", r) req := httptest.NewRequest(http.MethodPost, "/", r)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
req.Header.Set(HeaderContentType, ctype) req.Header.Set(HeaderContentType, ctype)
@ -378,7 +378,7 @@ func testBindOkay(assert *assert.Assertions, r io.Reader, ctype string) {
func testBindError(assert *assert.Assertions, r io.Reader, ctype string, expectedInternal error) { func testBindError(assert *assert.Assertions, r io.Reader, ctype string, expectedInternal error) {
e := New() e := New()
req := httptest.NewRequest(POST, "/", r) req := httptest.NewRequest(http.MethodPost, "/", r)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
req.Header.Set(HeaderContentType, ctype) req.Header.Set(HeaderContentType, ctype)

View File

@ -29,7 +29,7 @@ func (t *Template) Render(w io.Writer, name string, data interface{}, c Context)
func TestContext(t *testing.T) { func TestContext(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(POST, "/", strings.NewReader(userJSON)) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec).(*context) c := e.NewContext(req, rec).(*context)
@ -73,7 +73,7 @@ func TestContext(t *testing.T) {
} }
// JSON with "?pretty" // JSON with "?pretty"
req = httptest.NewRequest(GET, "/?pretty", nil) req = httptest.NewRequest(http.MethodGet, "/?pretty", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*context) c = e.NewContext(req, rec).(*context)
err = c.JSON(http.StatusOK, user{1, "Jon Snow"}) err = c.JSON(http.StatusOK, user{1, "Jon Snow"})
@ -82,7 +82,7 @@ func TestContext(t *testing.T) {
assert.Equal(MIMEApplicationJSONCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(MIMEApplicationJSONCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(userJSONPretty, rec.Body.String()) assert.Equal(userJSONPretty, rec.Body.String())
} }
req = httptest.NewRequest(GET, "/", nil) // reset req = httptest.NewRequest(http.MethodGet, "/", nil) // reset
// JSONPretty // JSONPretty
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
@ -122,7 +122,7 @@ func TestContext(t *testing.T) {
} }
// XML with "?pretty" // XML with "?pretty"
req = httptest.NewRequest(GET, "/?pretty", nil) req = httptest.NewRequest(http.MethodGet, "/?pretty", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*context) c = e.NewContext(req, rec).(*context)
err = c.XML(http.StatusOK, user{1, "Jon Snow"}) err = c.XML(http.StatusOK, user{1, "Jon Snow"})
@ -131,7 +131,7 @@ func TestContext(t *testing.T) {
assert.Equal(MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType))
assert.Equal(xml.Header+userXMLPretty, rec.Body.String()) assert.Equal(xml.Header+userXMLPretty, rec.Body.String())
} }
req = httptest.NewRequest(GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
// XML (error) // XML (error)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
@ -227,7 +227,7 @@ func TestContext(t *testing.T) {
func TestContextCookie(t *testing.T) { func TestContextCookie(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
theme := "theme=light" theme := "theme=light"
user := "user=Jon Snow" user := "user=Jon Snow"
req.Header.Add(HeaderCookie, theme) req.Header.Add(HeaderCookie, theme)
@ -276,23 +276,23 @@ func TestContextPath(t *testing.T) {
e := New() e := New()
r := e.Router() r := e.Router()
r.Add(GET, "/users/:id", nil) r.Add(http.MethodGet, "/users/:id", nil)
c := e.NewContext(nil, nil) c := e.NewContext(nil, nil)
r.Find(GET, "/users/1", c) r.Find(http.MethodGet, "/users/1", c)
assert := assert.New(t) assert := assert.New(t)
assert.Equal("/users/:id", c.Path()) assert.Equal("/users/:id", c.Path())
r.Add(GET, "/users/:uid/files/:fid", nil) r.Add(http.MethodGet, "/users/:uid/files/:fid", nil)
c = e.NewContext(nil, nil) c = e.NewContext(nil, nil)
r.Find(GET, "/users/1/files/1", c) r.Find(http.MethodGet, "/users/1/files/1", c)
assert.Equal("/users/:uid/files/:fid", c.Path()) assert.Equal("/users/:uid/files/:fid", c.Path())
} }
func TestContextPathParam(t *testing.T) { func TestContextPathParam(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
c := e.NewContext(req, nil) c := e.NewContext(req, nil)
// ParamNames // ParamNames
@ -313,7 +313,7 @@ func TestContextFormValue(t *testing.T) {
f.Set("email", "jon@labstack.com") f.Set("email", "jon@labstack.com")
e := New() e := New()
req := httptest.NewRequest(POST, "/", strings.NewReader(f.Encode())) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode()))
req.Header.Add(HeaderContentType, MIMEApplicationForm) req.Header.Add(HeaderContentType, MIMEApplicationForm)
c := e.NewContext(req, nil) c := e.NewContext(req, nil)
@ -335,7 +335,7 @@ func TestContextQueryParam(t *testing.T) {
q := make(url.Values) q := make(url.Values)
q.Set("name", "Jon Snow") q.Set("name", "Jon Snow")
q.Set("email", "jon@labstack.com") q.Set("email", "jon@labstack.com")
req := httptest.NewRequest(GET, "/?"+q.Encode(), nil) req := httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil)
e := New() e := New()
c := e.NewContext(req, nil) c := e.NewContext(req, nil)
@ -359,7 +359,7 @@ func TestContextFormFile(t *testing.T) {
w.Write([]byte("test")) w.Write([]byte("test"))
} }
mr.Close() mr.Close()
req := httptest.NewRequest(POST, "/", buf) req := httptest.NewRequest(http.MethodPost, "/", buf)
req.Header.Set(HeaderContentType, mr.FormDataContentType()) req.Header.Set(HeaderContentType, mr.FormDataContentType())
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
@ -375,7 +375,7 @@ func TestContextMultipartForm(t *testing.T) {
mw := multipart.NewWriter(buf) mw := multipart.NewWriter(buf)
mw.WriteField("name", "Jon Snow") mw.WriteField("name", "Jon Snow")
mw.Close() mw.Close()
req := httptest.NewRequest(POST, "/", buf) req := httptest.NewRequest(http.MethodPost, "/", buf)
req.Header.Set(HeaderContentType, mw.FormDataContentType()) req.Header.Set(HeaderContentType, mw.FormDataContentType())
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
@ -387,7 +387,7 @@ func TestContextMultipartForm(t *testing.T) {
func TestContextRedirect(t *testing.T) { func TestContextRedirect(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
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"))
@ -408,12 +408,12 @@ func TestContextHandler(t *testing.T) {
r := e.Router() r := e.Router()
b := new(bytes.Buffer) b := new(bytes.Buffer)
r.Add(GET, "/handler", func(Context) error { r.Add(http.MethodGet, "/handler", func(Context) error {
_, err := b.Write([]byte("handler")) _, err := b.Write([]byte("handler"))
return err return err
}) })
c := e.NewContext(nil, nil) c := e.NewContext(nil, nil)
r.Find(GET, "/handler", c) r.Find(http.MethodGet, "/handler", c)
c.Handler()(c) c.Handler()(c)
assert.Equal(t, "handler", b.String()) assert.Equal(t, "handler", b.String())
} }

53
echo.go
View File

@ -128,20 +128,6 @@ type (
} }
) )
// HTTP methods
const (
CONNECT = "CONNECT"
DELETE = "DELETE"
GET = "GET"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
PATCH = "PATCH"
POST = "POST"
PROPFIND = "PROPFIND"
PUT = "PUT"
TRACE = "TRACE"
)
// MIME types // MIME types
const ( const (
MIMEApplicationJSON = "application/json" MIMEApplicationJSON = "application/json"
@ -165,6 +151,7 @@ const (
const ( const (
charsetUTF8 = "charset=UTF-8" charsetUTF8 = "charset=UTF-8"
PROPFIND = "PROPFIND"
) )
// Headers // Headers
@ -234,16 +221,16 @@ ____________________________________O/_______
var ( var (
methods = [...]string{ methods = [...]string{
CONNECT, http.MethodConnect,
DELETE, http.MethodDelete,
GET, http.MethodGet,
HEAD, http.MethodHead,
OPTIONS, http.MethodOptions,
PATCH, http.MethodPatch,
POST, http.MethodPost,
PROPFIND, PROPFIND,
PUT, http.MethodPut,
TRACE, http.MethodTrace,
} }
) )
@ -345,7 +332,7 @@ func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
// Send response // Send response
if !c.Response().Committed { if !c.Response().Committed {
if c.Request().Method == HEAD { // Issue #608 if c.Request().Method == http.MethodHead { // Issue #608
err = c.NoContent(code) err = c.NoContent(code)
} else { } else {
err = c.JSON(code, msg) err = c.JSON(code, msg)
@ -369,55 +356,55 @@ func (e *Echo) Use(middleware ...MiddlewareFunc) {
// CONNECT registers a new CONNECT route for a path with matching handler in the // CONNECT registers a new CONNECT route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(CONNECT, path, h, m...) return e.Add(http.MethodConnect, path, h, m...)
} }
// DELETE registers a new DELETE route for a path with matching handler in the router // DELETE registers a new DELETE route for a path with matching handler in the router
// with optional route-level middleware. // with optional route-level middleware.
func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(DELETE, path, h, m...) return e.Add(http.MethodDelete, path, h, m...)
} }
// GET registers a new GET route for a path with matching handler in the router // GET registers a new GET route for a path with matching handler in the router
// with optional route-level middleware. // with optional route-level middleware.
func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(GET, path, h, m...) return e.Add(http.MethodGet, path, h, m...)
} }
// HEAD registers a new HEAD route for a path with matching handler in the // HEAD registers a new HEAD route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(HEAD, path, h, m...) return e.Add(http.MethodHead, path, h, m...)
} }
// OPTIONS registers a new OPTIONS route for a path with matching handler in the // OPTIONS registers a new OPTIONS route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(OPTIONS, path, h, m...) return e.Add(http.MethodOptions, path, h, m...)
} }
// PATCH registers a new PATCH route for a path with matching handler in the // PATCH registers a new PATCH route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(PATCH, path, h, m...) return e.Add(http.MethodPatch, path, h, m...)
} }
// POST registers a new POST route for a path with matching handler in the // POST registers a new POST route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(POST, path, h, m...) return e.Add(http.MethodPost, path, h, m...)
} }
// PUT registers a new PUT route for a path with matching handler in the // PUT registers a new PUT route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(PUT, path, h, m...) return e.Add(http.MethodPut, path, h, m...)
} }
// TRACE registers a new TRACE route for a path with matching handler in the // TRACE registers a new TRACE route for a path with matching handler in the
// router with optional route-level middleware. // router with optional route-level middleware.
func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return e.Add(TRACE, path, h, m...) return e.Add(http.MethodTrace, path, h, m...)
} }
// Any registers a new route for all HTTP methods and path with matching handler // Any registers a new route for all HTTP methods and path with matching handler

View File

@ -43,7 +43,7 @@ const userXMLPretty = `<user>
func TestEcho(t *testing.T) { func TestEcho(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
@ -62,28 +62,28 @@ func TestEchoStatic(t *testing.T) {
// OK // OK
e.Static("/images", "_fixture/images") e.Static("/images", "_fixture/images")
c, b := request(GET, "/images/walle.png", e) c, b := request(http.MethodGet, "/images/walle.png", e)
assert.Equal(http.StatusOK, c) assert.Equal(http.StatusOK, c)
assert.NotEmpty(b) assert.NotEmpty(b)
// No file // No file
e.Static("/images", "_fixture/scripts") e.Static("/images", "_fixture/scripts")
c, _ = request(GET, "/images/bolt.png", e) c, _ = request(http.MethodGet, "/images/bolt.png", e)
assert.Equal(http.StatusNotFound, c) assert.Equal(http.StatusNotFound, c)
// Directory // Directory
e.Static("/images", "_fixture/images") e.Static("/images", "_fixture/images")
c, _ = request(GET, "/images", e) c, _ = request(http.MethodGet, "/images", e)
assert.Equal(http.StatusNotFound, c) assert.Equal(http.StatusNotFound, c)
// Directory with index.html // Directory with index.html
e.Static("/", "_fixture") e.Static("/", "_fixture")
c, r := request(GET, "/", e) c, r := request(http.MethodGet, "/", e)
assert.Equal(http.StatusOK, c) assert.Equal(http.StatusOK, c)
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>")) assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))
// Sub-directory with index.html // Sub-directory with index.html
c, r = request(GET, "/folder", e) c, r = request(http.MethodGet, "/folder", e)
assert.Equal(http.StatusOK, c) assert.Equal(http.StatusOK, c)
assert.Equal(true, strings.HasPrefix(r, "<!doctype html>")) assert.Equal(true, strings.HasPrefix(r, "<!doctype html>"))
} }
@ -91,7 +91,7 @@ func TestEchoStatic(t *testing.T) {
func TestEchoFile(t *testing.T) { func TestEchoFile(t *testing.T) {
e := New() e := New()
e.File("/walle", "_fixture/images/walle.png") e.File("/walle", "_fixture/images/walle.png")
c, b := request(GET, "/walle", e) c, b := request(http.MethodGet, "/walle", e)
assert.Equal(t, http.StatusOK, c) assert.Equal(t, http.StatusOK, c)
assert.NotEmpty(t, b) assert.NotEmpty(t, b)
} }
@ -134,7 +134,7 @@ func TestEchoMiddleware(t *testing.T) {
return c.String(http.StatusOK, "OK") return c.String(http.StatusOK, "OK")
}) })
c, b := request(GET, "/", e) c, b := request(http.MethodGet, "/", e)
assert.Equal(t, "-1123", buf.String()) assert.Equal(t, "-1123", buf.String())
assert.Equal(t, http.StatusOK, c) assert.Equal(t, http.StatusOK, c)
assert.Equal(t, "OK", b) assert.Equal(t, "OK", b)
@ -148,7 +148,7 @@ func TestEchoMiddlewareError(t *testing.T) {
} }
}) })
e.GET("/", NotFoundHandler) e.GET("/", NotFoundHandler)
c, _ := request(GET, "/", e) c, _ := request(http.MethodGet, "/", e)
assert.Equal(t, http.StatusInternalServerError, c) assert.Equal(t, http.StatusInternalServerError, c)
} }
@ -160,14 +160,14 @@ func TestEchoHandler(t *testing.T) {
return c.String(http.StatusOK, "OK") return c.String(http.StatusOK, "OK")
}) })
c, b := request(GET, "/ok", e) c, b := request(http.MethodGet, "/ok", e)
assert.Equal(t, http.StatusOK, c) assert.Equal(t, http.StatusOK, c)
assert.Equal(t, "OK", b) assert.Equal(t, "OK", b)
} }
func TestEchoWrapHandler(t *testing.T) { func TestEchoWrapHandler(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := WrapHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := WrapHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -182,7 +182,7 @@ func TestEchoWrapHandler(t *testing.T) {
func TestEchoWrapMiddleware(t *testing.T) { func TestEchoWrapMiddleware(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
@ -204,47 +204,47 @@ func TestEchoWrapMiddleware(t *testing.T) {
func TestEchoConnect(t *testing.T) { func TestEchoConnect(t *testing.T) {
e := New() e := New()
testMethod(t, CONNECT, "/", e) testMethod(t, http.MethodConnect, "/", e)
} }
func TestEchoDelete(t *testing.T) { func TestEchoDelete(t *testing.T) {
e := New() e := New()
testMethod(t, DELETE, "/", e) testMethod(t, http.MethodDelete, "/", e)
} }
func TestEchoGet(t *testing.T) { func TestEchoGet(t *testing.T) {
e := New() e := New()
testMethod(t, GET, "/", e) testMethod(t, http.MethodGet, "/", e)
} }
func TestEchoHead(t *testing.T) { func TestEchoHead(t *testing.T) {
e := New() e := New()
testMethod(t, HEAD, "/", e) testMethod(t, http.MethodHead, "/", e)
} }
func TestEchoOptions(t *testing.T) { func TestEchoOptions(t *testing.T) {
e := New() e := New()
testMethod(t, OPTIONS, "/", e) testMethod(t, http.MethodOptions, "/", e)
} }
func TestEchoPatch(t *testing.T) { func TestEchoPatch(t *testing.T) {
e := New() e := New()
testMethod(t, PATCH, "/", e) testMethod(t, http.MethodPatch, "/", e)
} }
func TestEchoPost(t *testing.T) { func TestEchoPost(t *testing.T) {
e := New() e := New()
testMethod(t, POST, "/", e) testMethod(t, http.MethodPost, "/", e)
} }
func TestEchoPut(t *testing.T) { func TestEchoPut(t *testing.T) {
e := New() e := New()
testMethod(t, PUT, "/", e) testMethod(t, http.MethodPut, "/", e)
} }
func TestEchoTrace(t *testing.T) { func TestEchoTrace(t *testing.T) {
e := New() e := New()
testMethod(t, TRACE, "/", e) testMethod(t, http.MethodTrace, "/", e)
} }
func TestEchoAny(t *testing.T) { // JFC func TestEchoAny(t *testing.T) { // JFC
@ -256,7 +256,7 @@ func TestEchoAny(t *testing.T) { // JFC
func TestEchoMatch(t *testing.T) { // JFC func TestEchoMatch(t *testing.T) { // JFC
e := New() e := New()
e.Match([]string{GET, POST}, "/", func(c Context) error { e.Match([]string{http.MethodGet, http.MethodPost}, "/", func(c Context) error {
return c.String(http.StatusOK, "Match") return c.String(http.StatusOK, "Match")
}) })
} }
@ -284,10 +284,10 @@ func TestEchoURL(t *testing.T) {
func TestEchoRoutes(t *testing.T) { func TestEchoRoutes(t *testing.T) {
e := New() e := New()
routes := []*Route{ routes := []*Route{
{GET, "/users/:user/events", ""}, {http.MethodGet, "/users/:user/events", ""},
{GET, "/users/:user/events/public", ""}, {http.MethodGet, "/users/:user/events/public", ""},
{POST, "/repos/:owner/:repo/git/refs", ""}, {http.MethodPost, "/repos/:owner/:repo/git/refs", ""},
{POST, "/repos/:owner/:repo/git/tags", ""}, {http.MethodPost, "/repos/:owner/:repo/git/tags", ""},
} }
for _, r := range routes { for _, r := range routes {
e.Add(r.Method, r.Path, func(c Context) error { e.Add(r.Method, r.Path, func(c Context) error {
@ -316,7 +316,7 @@ func TestEchoEncodedPath(t *testing.T) {
e.GET("/:id", func(c Context) error { e.GET("/:id", func(c Context) error {
return c.NoContent(http.StatusOK) return c.NoContent(http.StatusOK)
}) })
req := httptest.NewRequest(GET, "/with%2Fslash", nil) req := httptest.NewRequest(http.MethodGet, "/with%2Fslash", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
@ -368,21 +368,21 @@ func TestEchoGroup(t *testing.T) {
}) })
g3.GET("", h) g3.GET("", h)
request(GET, "/users", e) request(http.MethodGet, "/users", e)
assert.Equal(t, "0", buf.String()) assert.Equal(t, "0", buf.String())
buf.Reset() buf.Reset()
request(GET, "/group1", e) request(http.MethodGet, "/group1", e)
assert.Equal(t, "01", buf.String()) assert.Equal(t, "01", buf.String())
buf.Reset() buf.Reset()
request(GET, "/group2/group3", e) request(http.MethodGet, "/group2/group3", e)
assert.Equal(t, "023", buf.String()) assert.Equal(t, "023", buf.String())
} }
func TestEchoNotFound(t *testing.T) { func TestEchoNotFound(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/files", nil) req := httptest.NewRequest(http.MethodGet, "/files", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusNotFound, rec.Code) assert.Equal(t, http.StatusNotFound, rec.Code)
@ -393,7 +393,7 @@ 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!")
}) })
req := httptest.NewRequest(POST, "/", nil) req := httptest.NewRequest(http.MethodPost, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code) assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)

View File

@ -1,6 +1,7 @@
package echo package echo
import ( import (
"net/http"
"path" "path"
) )
@ -29,47 +30,47 @@ func (g *Group) Use(middleware ...MiddlewareFunc) {
// CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. // CONNECT implements `Echo#CONNECT()` for sub-routes within the Group.
func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(CONNECT, path, h, m...) return g.Add(http.MethodConnect, path, h, m...)
} }
// DELETE implements `Echo#DELETE()` for sub-routes within the Group. // DELETE implements `Echo#DELETE()` for sub-routes within the Group.
func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(DELETE, path, h, m...) return g.Add(http.MethodDelete, path, h, m...)
} }
// GET implements `Echo#GET()` for sub-routes within the Group. // GET implements `Echo#GET()` for sub-routes within the Group.
func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(GET, path, h, m...) return g.Add(http.MethodGet, path, h, m...)
} }
// HEAD implements `Echo#HEAD()` for sub-routes within the Group. // HEAD implements `Echo#HEAD()` for sub-routes within the Group.
func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(HEAD, path, h, m...) return g.Add(http.MethodHead, path, h, m...)
} }
// OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. // OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group.
func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(OPTIONS, path, h, m...) return g.Add(http.MethodOptions, path, h, m...)
} }
// PATCH implements `Echo#PATCH()` for sub-routes within the Group. // PATCH implements `Echo#PATCH()` for sub-routes within the Group.
func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(PATCH, path, h, m...) return g.Add(http.MethodPatch, path, h, m...)
} }
// POST implements `Echo#POST()` for sub-routes within the Group. // POST implements `Echo#POST()` for sub-routes within the Group.
func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(POST, path, h, m...) return g.Add(http.MethodPost, path, h, m...)
} }
// PUT implements `Echo#PUT()` for sub-routes within the Group. // PUT implements `Echo#PUT()` for sub-routes within the Group.
func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(PUT, path, h, m...) return g.Add(http.MethodPut, path, h, m...)
} }
// TRACE implements `Echo#TRACE()` for sub-routes within the Group. // TRACE implements `Echo#TRACE()` for sub-routes within the Group.
func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
return g.Add(TRACE, path, h, m...) return g.Add(http.MethodTrace, path, h, m...)
} }
// Any implements `Echo#Any()` for sub-routes within the Group. // Any implements `Echo#Any()` for sub-routes within the Group.

View File

@ -1,6 +1,7 @@
package echo package echo
import ( import (
"net/http"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -20,7 +21,7 @@ func TestGroup(t *testing.T) {
g.PUT("/", h) g.PUT("/", h)
g.TRACE("/", h) g.TRACE("/", h)
g.Any("/", h) g.Any("/", h)
g.Match([]string{GET, POST}, "/", h) g.Match([]string{http.MethodGet, http.MethodPost}, "/", h)
g.Static("/static", "/tmp") g.Static("/static", "/tmp")
g.File("/walle", "_fixture/images//walle.png") g.File("/walle", "_fixture/images//walle.png")
} }
@ -59,8 +60,8 @@ func TestGroupRouteMiddleware(t *testing.T) {
g.GET("/404", h, m4) g.GET("/404", h, m4)
g.GET("/405", h, m5) g.GET("/405", h, m5)
c, _ := request(GET, "/group/404", e) c, _ := request(http.MethodGet, "/group/404", e)
assert.Equal(t, 404, c) assert.Equal(t, 404, c)
c, _ = request(GET, "/group/405", e) c, _ = request(http.MethodGet, "/group/405", e)
assert.Equal(t, 405, c) assert.Equal(t, 405, c)
} }

View File

@ -13,7 +13,7 @@ import (
func TestBasicAuth(t *testing.T) { func TestBasicAuth(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
res := httptest.NewRecorder() res := httptest.NewRecorder()
c := e.NewContext(req, res) c := e.NewContext(req, res)
f := func(u, p string, c echo.Context) (bool, error) { f := func(u, p string, c echo.Context) (bool, error) {

View File

@ -15,7 +15,7 @@ import (
func TestBodyDump(t *testing.T) { func TestBodyDump(t *testing.T) {
e := echo.New() e := echo.New()
hw := "Hello, World!" hw := "Hello, World!"
req := httptest.NewRequest(echo.POST, "/", strings.NewReader(hw)) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(hw))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := func(c echo.Context) error { h := func(c echo.Context) error {
@ -55,7 +55,7 @@ func TestBodyDump(t *testing.T) {
func TestBodyDumpFails(t *testing.T) { func TestBodyDumpFails(t *testing.T) {
e := echo.New() e := echo.New()
hw := "Hello, World!" hw := "Hello, World!"
req := httptest.NewRequest(echo.POST, "/", strings.NewReader(hw)) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(hw))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := func(c echo.Context) error { h := func(c echo.Context) error {

View File

@ -14,7 +14,7 @@ import (
func TestBodyLimit(t *testing.T) { func TestBodyLimit(t *testing.T) {
e := echo.New() e := echo.New()
hw := []byte("Hello, World!") hw := []byte("Hello, World!")
req := httptest.NewRequest(echo.POST, "/", bytes.NewReader(hw)) req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := func(c echo.Context) error { h := func(c echo.Context) error {
@ -38,7 +38,7 @@ func TestBodyLimit(t *testing.T) {
assert.Equal(http.StatusRequestEntityTooLarge, he.Code) assert.Equal(http.StatusRequestEntityTooLarge, he.Code)
// Based on content read (within limit) // Based on content read (within limit)
req = httptest.NewRequest(echo.POST, "/", bytes.NewReader(hw)) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw))
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
if assert.NoError(BodyLimit("2M")(h)(c)) { if assert.NoError(BodyLimit("2M")(h)(c)) {
@ -47,7 +47,7 @@ func TestBodyLimit(t *testing.T) {
} }
// Based on content read (overlimit) // Based on content read (overlimit)
req = httptest.NewRequest(echo.POST, "/", bytes.NewReader(hw)) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw))
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
he = BodyLimit("2B")(h)(c).(*echo.HTTPError) he = BodyLimit("2B")(h)(c).(*echo.HTTPError)
@ -57,7 +57,7 @@ func TestBodyLimit(t *testing.T) {
func TestBodyLimitReader(t *testing.T) { func TestBodyLimitReader(t *testing.T) {
hw := []byte("Hello, World!") hw := []byte("Hello, World!")
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.POST, "/", bytes.NewReader(hw)) req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
config := BodyLimitConfig{ config := BodyLimitConfig{

View File

@ -14,7 +14,7 @@ import (
func TestGzip(t *testing.T) { func TestGzip(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
@ -30,7 +30,7 @@ func TestGzip(t *testing.T) {
assert.Equal("test", rec.Body.String()) assert.Equal("test", rec.Body.String())
// Gzip // Gzip
req = httptest.NewRequest(echo.GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
@ -48,7 +48,7 @@ func TestGzip(t *testing.T) {
func TestGzipNoContent(t *testing.T) { func TestGzipNoContent(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
@ -68,7 +68,7 @@ func TestGzipErrorReturned(t *testing.T) {
e.GET("/", func(c echo.Context) error { e.GET("/", func(c echo.Context) error {
return echo.ErrNotFound return echo.ErrNotFound
}) })
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
@ -81,7 +81,7 @@ func TestGzipWithStatic(t *testing.T) {
e := echo.New() e := echo.New()
e.Use(Gzip()) e.Use(Gzip())
e.Static("/test", "../_fixture/images") e.Static("/test", "../_fixture/images")
req := httptest.NewRequest(echo.GET, "/test/walle.png", nil) req := httptest.NewRequest(http.MethodGet, "/test/walle.png", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)

View File

@ -52,7 +52,7 @@ var (
DefaultCORSConfig = CORSConfig{ DefaultCORSConfig = CORSConfig{
Skipper: DefaultSkipper, Skipper: DefaultSkipper,
AllowOrigins: []string{"*"}, AllowOrigins: []string{"*"},
AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE}, AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
} }
) )
@ -105,7 +105,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
} }
// Simple request // Simple request
if req.Method != echo.OPTIONS { if req.Method != http.MethodOptions {
res.Header().Add(echo.HeaderVary, echo.HeaderOrigin) res.Header().Add(echo.HeaderVary, echo.HeaderOrigin)
res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowOrigin) res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowOrigin)
if config.AllowCredentials { if config.AllowCredentials {

View File

@ -1,6 +1,7 @@
package middleware package middleware
import ( import (
"net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -12,7 +13,7 @@ func TestCORS(t *testing.T) {
e := echo.New() e := echo.New()
// Wildcard origin // Wildcard origin
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := CORS()(echo.NotFoundHandler) h := CORS()(echo.NotFoundHandler)
@ -20,7 +21,7 @@ func TestCORS(t *testing.T) {
assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
// Allow origins // Allow origins
req = httptest.NewRequest(echo.GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
h = CORSWithConfig(CORSConfig{ h = CORSWithConfig(CORSConfig{
@ -31,7 +32,7 @@ func TestCORS(t *testing.T) {
assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
// Preflight request // Preflight request
req = httptest.NewRequest(echo.OPTIONS, "/", nil) req = httptest.NewRequest(http.MethodOptions, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
req.Header.Set(echo.HeaderOrigin, "localhost") req.Header.Set(echo.HeaderOrigin, "localhost")
@ -49,7 +50,7 @@ func TestCORS(t *testing.T) {
assert.Equal(t, "3600", rec.Header().Get(echo.HeaderAccessControlMaxAge)) assert.Equal(t, "3600", rec.Header().Get(echo.HeaderAccessControlMaxAge))
// Preflight request with `AllowOrigins` * // Preflight request with `AllowOrigins` *
req = httptest.NewRequest(echo.OPTIONS, "/", nil) req = httptest.NewRequest(http.MethodOptions, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
req.Header.Set(echo.HeaderOrigin, "localhost") req.Header.Set(echo.HeaderOrigin, "localhost")

View File

@ -135,7 +135,7 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
} }
switch req.Method { switch req.Method {
case echo.GET, echo.HEAD, echo.OPTIONS, echo.TRACE: case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
default: default:
// Validate token only for requests which are not defined as 'safe' by RFC7231 // Validate token only for requests which are not defined as 'safe' by RFC7231
clientToken, err := extractor(c) clientToken, err := extractor(c)

View File

@ -14,7 +14,7 @@ import (
func TestCSRF(t *testing.T) { func TestCSRF(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
csrf := CSRFWithConfig(CSRFConfig{ csrf := CSRFWithConfig(CSRFConfig{
@ -29,13 +29,13 @@ func TestCSRF(t *testing.T) {
assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf") assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf")
// Without CSRF cookie // Without CSRF cookie
req = httptest.NewRequest(echo.POST, "/", nil) req = httptest.NewRequest(http.MethodPost, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
assert.Error(t, h(c)) assert.Error(t, h(c))
// Empty/invalid CSRF token // Empty/invalid CSRF token
req = httptest.NewRequest(echo.POST, "/", nil) req = httptest.NewRequest(http.MethodPost, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
req.Header.Set(echo.HeaderXCSRFToken, "") req.Header.Set(echo.HeaderXCSRFToken, "")
@ -54,7 +54,7 @@ func TestCSRFTokenFromForm(t *testing.T) {
f := make(url.Values) f := make(url.Values)
f.Set("csrf", "token") f.Set("csrf", "token")
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.POST, "/", strings.NewReader(f.Encode())) req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode()))
req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)
c := e.NewContext(req, nil) c := e.NewContext(req, nil)
token, err := csrfTokenFromForm("csrf")(c) token, err := csrfTokenFromForm("csrf")(c)
@ -69,7 +69,7 @@ func TestCSRFTokenFromQuery(t *testing.T) {
q := make(url.Values) q := make(url.Values)
q.Set("csrf", "token") q.Set("csrf", "token")
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)
req.URL.RawQuery = q.Encode() req.URL.RawQuery = q.Encode()
c := e.NewContext(req, nil) c := e.NewContext(req, nil)

View File

@ -37,7 +37,7 @@ func TestJWTRace(t *testing.T) {
})(handler) })(handler)
makeReq := func(token string) echo.Context { makeReq := func(token string) echo.Context {
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
res := httptest.NewRecorder() res := httptest.NewRecorder()
req.Header.Set(echo.HeaderAuthorization, DefaultJWTConfig.AuthScheme+" "+token) req.Header.Set(echo.HeaderAuthorization, DefaultJWTConfig.AuthScheme+" "+token)
c := e.NewContext(req, res) c := e.NewContext(req, res)
@ -189,7 +189,7 @@ func TestJWT(t *testing.T) {
tc.reqURL = "/" tc.reqURL = "/"
} }
req := httptest.NewRequest(echo.GET, tc.reqURL, nil) req := httptest.NewRequest(http.MethodGet, tc.reqURL, nil)
res := httptest.NewRecorder() res := httptest.NewRecorder()
req.Header.Set(echo.HeaderAuthorization, tc.hdrAuth) req.Header.Set(echo.HeaderAuthorization, tc.hdrAuth)
req.Header.Set(echo.HeaderCookie, tc.hdrCookie) req.Header.Set(echo.HeaderCookie, tc.hdrCookie)

View File

@ -13,7 +13,7 @@ import (
func TestKeyAuth(t *testing.T) { func TestKeyAuth(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
config := KeyAuthConfig{ config := KeyAuthConfig{
@ -68,7 +68,7 @@ func TestKeyAuth(t *testing.T) {
}) })
f := make(url.Values) f := make(url.Values)
f.Set("key", "valid-key") f.Set("key", "valid-key")
req = httptest.NewRequest(echo.POST, "/", strings.NewReader(f.Encode())) req = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode()))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
assert.NoError(h(c)) assert.NoError(h(c))

View File

@ -19,7 +19,7 @@ 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()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := Logger()(func(c echo.Context) error { h := Logger()(func(c echo.Context) error {
@ -46,7 +46,7 @@ func TestLogger(t *testing.T) {
h(c) h(c)
// Status 5xx with empty path // Status 5xx with empty path
req = httptest.NewRequest(echo.GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
h = Logger()(func(c echo.Context) error { h = Logger()(func(c echo.Context) error {
@ -57,7 +57,7 @@ func TestLogger(t *testing.T) {
func TestLoggerIPAddress(t *testing.T) { func TestLoggerIPAddress(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
@ -101,7 +101,7 @@ func TestLoggerTemplate(t *testing.T) {
return c.String(http.StatusOK, "Header Logged") return c.String(http.StatusOK, "Header Logged")
}) })
req := httptest.NewRequest(echo.GET, "/?username=apagano-param&password=secret", nil) req := httptest.NewRequest(http.MethodGet, "/?username=apagano-param&password=secret", nil)
req.RequestURI = "/" req.RequestURI = "/"
req.Header.Add(echo.HeaderXRealIP, "127.0.0.1") req.Header.Add(echo.HeaderXRealIP, "127.0.0.1")
req.Header.Add("Referer", "google.com") req.Header.Add("Referer", "google.com")
@ -159,7 +159,7 @@ func TestLoggerCustomTimestamp(t *testing.T) {
return c.String(http.StatusOK, "custom time stamp test") return c.String(http.StatusOK, "custom time stamp test")
}) })
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)

View File

@ -1,6 +1,10 @@
package middleware package middleware
import "github.com/labstack/echo" import (
"net/http"
"github.com/labstack/echo"
)
type ( type (
// MethodOverrideConfig defines the config for MethodOverride middleware. // MethodOverrideConfig defines the config for MethodOverride middleware.
@ -52,7 +56,7 @@ func MethodOverrideWithConfig(config MethodOverrideConfig) echo.MiddlewareFunc {
} }
req := c.Request() req := c.Request()
if req.Method == echo.POST { if req.Method == http.MethodPost {
m := config.Getter(c) m := config.Getter(c)
if m != "" { if m != "" {
req.Method = m req.Method = m

View File

@ -18,32 +18,32 @@ func TestMethodOverride(t *testing.T) {
} }
// Override with http header // Override with http header
req := httptest.NewRequest(echo.POST, "/", nil) req := httptest.NewRequest(http.MethodPost, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
req.Header.Set(echo.HeaderXHTTPMethodOverride, echo.DELETE) req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete)
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
m(h)(c) m(h)(c)
assert.Equal(t, echo.DELETE, req.Method) assert.Equal(t, http.MethodDelete, req.Method)
// Override with form parameter // Override with form parameter
m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromForm("_method")}) m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromForm("_method")})
req = httptest.NewRequest(echo.POST, "/", bytes.NewReader([]byte("_method="+echo.DELETE))) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader([]byte("_method="+http.MethodDelete)))
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
m(h)(c) m(h)(c)
assert.Equal(t, echo.DELETE, req.Method) assert.Equal(t, http.MethodDelete, req.Method)
// Override with query parameter // Override with query parameter
m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromQuery("_method")}) m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromQuery("_method")})
req = httptest.NewRequest(echo.POST, "/?_method="+echo.DELETE, nil) req = httptest.NewRequest(http.MethodPost, "/?_method="+http.MethodDelete, nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
m(h)(c) m(h)(c)
assert.Equal(t, echo.DELETE, req.Method) assert.Equal(t, http.MethodDelete, req.Method)
// Ignore `GET` // Ignore `GET`
req = httptest.NewRequest(echo.GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderXHTTPMethodOverride, echo.DELETE) req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete)
assert.Equal(t, echo.GET, req.Method) assert.Equal(t, http.MethodGet, req.Method)
} }

View File

@ -18,7 +18,7 @@ func proxyHTTP(tgt *ProxyTarget, c echo.Context, config ProxyConfig) http.Handle
desc = fmt.Sprintf("%s(%s)", tgt.Name, tgt.URL.String()) desc = fmt.Sprintf("%s(%s)", tgt.Name, tgt.URL.String())
} }
c.Logger().Errorf("remote %s unreachable, could not forward: %v", desc, err) c.Logger().Errorf("remote %s unreachable, could not forward: %v", desc, err)
c.Error(echo.ErrServiceUnavailable) c.Error(echo.NewHTTPError(http.StatusServiceUnavailable))
} }
proxy.Transport = config.Transport proxy.Transport = config.Transport
return proxy return proxy

View File

@ -3,12 +3,13 @@
package middleware package middleware
import ( import (
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"testing" "testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
) )
func TestProxy_1_11(t *testing.T) { func TestProxy_1_11(t *testing.T) {
@ -40,7 +41,7 @@ func TestProxy_1_11(t *testing.T) {
// Random // Random
e := echo.New() e := echo.New()
e.Use(Proxy(rb)) e.Use(Proxy(rb))
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := newCloseNotifyRecorder() rec := newCloseNotifyRecorder()
// Remote unreachable // Remote unreachable

View File

@ -70,7 +70,7 @@ func TestProxy(t *testing.T) {
// Random // Random
e := echo.New() e := echo.New()
e.Use(Proxy(rb)) e.Use(Proxy(rb))
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := newCloseNotifyRecorder() rec := newCloseNotifyRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
body := rec.Body.String() body := rec.Body.String()

View File

@ -14,7 +14,7 @@ func TestRecover(t *testing.T) {
e := echo.New() e := echo.New()
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
e.Logger.SetOutput(buf) e.Logger.SetOutput(buf)
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := Recover()(echo.HandlerFunc(func(c echo.Context) error { h := Recover()(echo.HandlerFunc(func(c echo.Context) error {

View File

@ -75,7 +75,7 @@ func redirectTest(fn middlewareGenerator, host string, header http.Header) *http
next := func(c echo.Context) (err error) { next := func(c echo.Context) (err error) {
return c.NoContent(http.StatusOK) return c.NoContent(http.StatusOK)
} }
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = host req.Host = host
if header != nil { if header != nil {
req.Header = header req.Header = header

View File

@ -11,7 +11,7 @@ import (
func TestRequestID(t *testing.T) { func TestRequestID(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
handler := func(c echo.Context) error { handler := func(c echo.Context) error {

View File

@ -2,6 +2,7 @@ package middleware
import ( import (
"io/ioutil" "io/ioutil"
"net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -19,7 +20,7 @@ func TestRewrite(t *testing.T) {
"/users/*/orders/*": "/user/$1/order/$2", "/users/*/orders/*": "/user/$1/order/$2",
}, },
})) }))
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
req.URL.Path = "/api/users" req.URL.Path = "/api/users"
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
@ -51,11 +52,11 @@ func TestEchoRewritePreMiddleware(t *testing.T) {
})) }))
// Route // Route
r.Add(echo.GET, "/new", func(c echo.Context) error { r.Add(http.MethodGet, "/new", func(c echo.Context) error {
return c.NoContent(200) return c.NoContent(200)
}) })
req := httptest.NewRequest(echo.GET, "/old", nil) req := httptest.NewRequest(http.MethodGet, "/old", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
assert.Equal(t, "/new", req.URL.Path) assert.Equal(t, "/new", req.URL.Path)
@ -74,15 +75,15 @@ func TestRewriteWithConfigPreMiddleware_Issue1143(t *testing.T) {
}, },
})) }))
r.Add(echo.GET, "/api/:version/hosts/:name", func(c echo.Context) error { r.Add(http.MethodGet, "/api/:version/hosts/:name", func(c echo.Context) error {
return c.String(200, "hosts") return c.String(200, "hosts")
}) })
r.Add(echo.GET, "/api/:version/eng", func(c echo.Context) error { r.Add(http.MethodGet, "/api/:version/eng", func(c echo.Context) error {
return c.String(200, "eng") return c.String(200, "eng")
}) })
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
req := httptest.NewRequest(echo.GET, "/api/v1/mgmt/proj/test/agt", nil) req := httptest.NewRequest(http.MethodGet, "/api/v1/mgmt/proj/test/agt", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
assert.Equal(t, "/api/v1/hosts/test", req.URL.Path) assert.Equal(t, "/api/v1/hosts/test", req.URL.Path)

View File

@ -11,7 +11,7 @@ import (
func TestSecure(t *testing.T) { func TestSecure(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := func(c echo.Context) error { h := func(c echo.Context) error {

View File

@ -11,7 +11,7 @@ import (
func TestAddTrailingSlash(t *testing.T) { func TestAddTrailingSlash(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/add-slash", nil) req := httptest.NewRequest(http.MethodGet, "/add-slash", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := AddTrailingSlash()(func(c echo.Context) error { h := AddTrailingSlash()(func(c echo.Context) error {
@ -24,7 +24,7 @@ func TestAddTrailingSlash(t *testing.T) {
assert.Equal("/add-slash/", req.RequestURI) assert.Equal("/add-slash/", req.RequestURI)
// With config // With config
req = httptest.NewRequest(echo.GET, "/add-slash?key=value", nil) req = httptest.NewRequest(http.MethodGet, "/add-slash?key=value", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
h = AddTrailingSlashWithConfig(TrailingSlashConfig{ h = AddTrailingSlashWithConfig(TrailingSlashConfig{
@ -39,7 +39,7 @@ func TestAddTrailingSlash(t *testing.T) {
func TestRemoveTrailingSlash(t *testing.T) { func TestRemoveTrailingSlash(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/remove-slash/", nil) req := httptest.NewRequest(http.MethodGet, "/remove-slash/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
h := RemoveTrailingSlash()(func(c echo.Context) error { h := RemoveTrailingSlash()(func(c echo.Context) error {
@ -53,7 +53,7 @@ func TestRemoveTrailingSlash(t *testing.T) {
assert.Equal("/remove-slash", req.RequestURI) assert.Equal("/remove-slash", req.RequestURI)
// With config // With config
req = httptest.NewRequest(echo.GET, "/remove-slash/?key=value", nil) req = httptest.NewRequest(http.MethodGet, "/remove-slash/?key=value", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
h = RemoveTrailingSlashWithConfig(TrailingSlashConfig{ h = RemoveTrailingSlashWithConfig(TrailingSlashConfig{
@ -66,7 +66,7 @@ func TestRemoveTrailingSlash(t *testing.T) {
assert.Equal("/remove-slash?key=value", rec.Header().Get(echo.HeaderLocation)) assert.Equal("/remove-slash?key=value", rec.Header().Get(echo.HeaderLocation))
// With bare URL // With bare URL
req = httptest.NewRequest(echo.GET, "http://localhost", nil) req = httptest.NewRequest(http.MethodGet, "http://localhost", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
h = RemoveTrailingSlash()(func(c echo.Context) error { h = RemoveTrailingSlash()(func(c echo.Context) error {

View File

@ -11,7 +11,7 @@ import (
func TestStatic(t *testing.T) { func TestStatic(t *testing.T) {
e := echo.New() e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
config := StaticConfig{ config := StaticConfig{
@ -28,7 +28,7 @@ func TestStatic(t *testing.T) {
} }
// File found // File found
req = httptest.NewRequest(echo.GET, "/images/walle.png", nil) req = httptest.NewRequest(http.MethodGet, "/images/walle.png", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
if assert.NoError(h(c)) { if assert.NoError(h(c)) {
@ -37,14 +37,14 @@ func TestStatic(t *testing.T) {
} }
// File not found // File not found
req = httptest.NewRequest(echo.GET, "/none", nil) req = httptest.NewRequest(http.MethodGet, "/none", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
he := h(c).(*echo.HTTPError) he := h(c).(*echo.HTTPError)
assert.Equal(http.StatusNotFound, he.Code) assert.Equal(http.StatusNotFound, he.Code)
// HTML5 // HTML5
req = httptest.NewRequest(echo.GET, "/random", nil) req = httptest.NewRequest(http.MethodGet, "/random", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
config.HTML5 = true config.HTML5 = true
@ -56,7 +56,7 @@ func TestStatic(t *testing.T) {
} }
// Browse // Browse
req = httptest.NewRequest(echo.GET, "/", nil) req = httptest.NewRequest(http.MethodGet, "/", nil)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec) c = e.NewContext(req, rec)
config.Root = "../_fixture/certs" config.Root = "../_fixture/certs"

View File

@ -1,6 +1,7 @@
package echo package echo
import ( import (
"net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -9,7 +10,7 @@ import (
func TestResponse(t *testing.T) { func TestResponse(t *testing.T) {
e := New() e := New()
req := httptest.NewRequest(GET, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec) c := e.NewContext(req, rec)
res := &Response{echo: e, Writer: rec} res := &Response{echo: e, Writer: rec}

View File

@ -1,5 +1,7 @@
package echo package echo
import "net/http"
type ( type (
// Router is the registry of all registered routes for an `Echo` instance for // Router is the registry of all registered routes for an `Echo` instance for
// request matching and URL path parameter parsing. // request matching and URL path parameter parsing.
@ -226,50 +228,50 @@ func (n *node) findChildByKind(t kind) *node {
func (n *node) addHandler(method string, h HandlerFunc) { func (n *node) addHandler(method string, h HandlerFunc) {
switch method { switch method {
case CONNECT: case http.MethodConnect:
n.methodHandler.connect = h n.methodHandler.connect = h
case DELETE: case http.MethodDelete:
n.methodHandler.delete = h n.methodHandler.delete = h
case GET: case http.MethodGet:
n.methodHandler.get = h n.methodHandler.get = h
case HEAD: case http.MethodHead:
n.methodHandler.head = h n.methodHandler.head = h
case OPTIONS: case http.MethodOptions:
n.methodHandler.options = h n.methodHandler.options = h
case PATCH: case http.MethodPatch:
n.methodHandler.patch = h n.methodHandler.patch = h
case POST: case http.MethodPost:
n.methodHandler.post = h n.methodHandler.post = h
case PROPFIND: case PROPFIND:
n.methodHandler.propfind = h n.methodHandler.propfind = h
case PUT: case http.MethodPut:
n.methodHandler.put = h n.methodHandler.put = h
case TRACE: case http.MethodTrace:
n.methodHandler.trace = h n.methodHandler.trace = h
} }
} }
func (n *node) findHandler(method string) HandlerFunc { func (n *node) findHandler(method string) HandlerFunc {
switch method { switch method {
case CONNECT: case http.MethodConnect:
return n.methodHandler.connect return n.methodHandler.connect
case DELETE: case http.MethodDelete:
return n.methodHandler.delete return n.methodHandler.delete
case GET: case http.MethodGet:
return n.methodHandler.get return n.methodHandler.get
case HEAD: case http.MethodHead:
return n.methodHandler.head return n.methodHandler.head
case OPTIONS: case http.MethodOptions:
return n.methodHandler.options return n.methodHandler.options
case PATCH: case http.MethodPatch:
return n.methodHandler.patch return n.methodHandler.patch
case POST: case http.MethodPost:
return n.methodHandler.post return n.methodHandler.post
case PROPFIND: case PROPFIND:
return n.methodHandler.propfind return n.methodHandler.propfind
case PUT: case http.MethodPut:
return n.methodHandler.put return n.methodHandler.put
case TRACE: case http.MethodTrace:
return n.methodHandler.trace return n.methodHandler.trace
default: default:
return nil return nil

View File

@ -505,12 +505,12 @@ func TestRouterStatic(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
path := "/folders/a/files/echo.gif" path := "/folders/a/files/echo.gif"
r.Add(GET, path, func(c Context) error { r.Add(http.MethodGet, path, func(c Context) error {
c.Set("path", path) c.Set("path", path)
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, path, c) r.Find(http.MethodGet, path, c)
c.handler(c) c.handler(c)
assert.Equal(t, path, c.Get("path")) assert.Equal(t, path, c.Get("path"))
} }
@ -518,23 +518,23 @@ func TestRouterStatic(t *testing.T) {
func TestRouterParam(t *testing.T) { func TestRouterParam(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
r.Add(GET, "/users/:id", func(c Context) error { r.Add(http.MethodGet, "/users/:id", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/1", c) r.Find(http.MethodGet, "/users/1", c)
assert.Equal(t, "1", c.Param("id")) assert.Equal(t, "1", c.Param("id"))
} }
func TestRouterTwoParam(t *testing.T) { func TestRouterTwoParam(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
r.Add(GET, "/users/:uid/files/:fid", func(Context) error { r.Add(http.MethodGet, "/users/:uid/files/:fid", func(Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/1/files/1", c) r.Find(http.MethodGet, "/users/1/files/1", c)
assert.Equal(t, "1", c.Param("uid")) assert.Equal(t, "1", c.Param("uid"))
assert.Equal(t, "1", c.Param("fid")) assert.Equal(t, "1", c.Param("fid"))
} }
@ -544,17 +544,17 @@ func TestRouterParamWithSlash(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
r.Add(GET, "/a/:b/c/d/:e", func(c Context) error { r.Add(http.MethodGet, "/a/:b/c/d/:e", func(c Context) error {
return nil return nil
}) })
r.Add(GET, "/a/:b/c/:d/:f", func(c Context) error { r.Add(http.MethodGet, "/a/:b/c/:d/:f", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
assert.NotPanics(t, func() { assert.NotPanics(t, func() {
r.Find(GET, "/a/1/c/d/2/3", c) r.Find(http.MethodGet, "/a/1/c/d/2/3", c)
}) })
} }
@ -563,24 +563,24 @@ func TestRouterMatchAny(t *testing.T) {
r := e.router r := e.router
// Routes // Routes
r.Add(GET, "/", func(Context) error { r.Add(http.MethodGet, "/", func(Context) error {
return nil return nil
}) })
r.Add(GET, "/*", func(Context) error { r.Add(http.MethodGet, "/*", func(Context) error {
return nil return nil
}) })
r.Add(GET, "/users/*", func(Context) error { r.Add(http.MethodGet, "/users/*", func(Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/", c) r.Find(http.MethodGet, "/", c)
assert.Equal(t, "", c.Param("*")) assert.Equal(t, "", c.Param("*"))
r.Find(GET, "/download", c) r.Find(http.MethodGet, "/download", c)
assert.Equal(t, "download", c.Param("*")) assert.Equal(t, "download", c.Param("*"))
r.Find(GET, "/users/joe", c) r.Find(http.MethodGet, "/users/joe", c)
assert.Equal(t, "joe", c.Param("*")) assert.Equal(t, "joe", c.Param("*"))
} }
@ -593,20 +593,20 @@ func TestRouterMatchAnyMultiLevel(t *testing.T) {
} }
// Routes // Routes
r.Add(GET, "/api/users/jack", handler) r.Add(http.MethodGet, "/api/users/jack", handler)
r.Add(GET, "/api/users/jill", handler) r.Add(http.MethodGet, "/api/users/jill", handler)
r.Add(GET, "/*", handler) r.Add(http.MethodGet, "/*", handler)
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/api/users/jack", c) r.Find(http.MethodGet, "/api/users/jack", c)
c.handler(c) c.handler(c)
assert.Equal(t, "/api/users/jack", c.Get("path")) assert.Equal(t, "/api/users/jack", c.Get("path"))
r.Find(GET, "/api/users/jill", c) r.Find(http.MethodGet, "/api/users/jill", c)
c.handler(c) c.handler(c)
assert.Equal(t, "/api/users/jill", c.Get("path")) assert.Equal(t, "/api/users/jill", c.Get("path"))
r.Find(GET, "/api/users/joe", c) r.Find(http.MethodGet, "/api/users/joe", c)
c.handler(c) c.handler(c)
assert.Equal(t, "/*", c.Get("path")) assert.Equal(t, "/*", c.Get("path"))
} }
@ -614,11 +614,11 @@ func TestRouterMatchAnyMultiLevel(t *testing.T) {
func TestRouterMicroParam(t *testing.T) { func TestRouterMicroParam(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
r.Add(GET, "/:a/:b/:c", func(c Context) error { r.Add(http.MethodGet, "/:a/:b/:c", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/1/2/3", c) r.Find(http.MethodGet, "/1/2/3", c)
assert.Equal(t, "1", c.Param("a")) assert.Equal(t, "1", c.Param("a"))
assert.Equal(t, "2", c.Param("b")) assert.Equal(t, "2", c.Param("b"))
assert.Equal(t, "3", c.Param("c")) assert.Equal(t, "3", c.Param("c"))
@ -629,12 +629,12 @@ func TestRouterMixParamMatchAny(t *testing.T) {
r := e.router r := e.router
// Route // Route
r.Add(GET, "/users/:id/*", func(c Context) error { r.Add(http.MethodGet, "/users/:id/*", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/joe/comments", c) r.Find(http.MethodGet, "/users/joe/comments", c)
c.handler(c) c.handler(c)
assert.Equal(t, "joe", c.Param("id")) assert.Equal(t, "joe", c.Param("id"))
} }
@ -644,27 +644,27 @@ func TestRouterMultiRoute(t *testing.T) {
r := e.router r := e.router
// Routes // Routes
r.Add(GET, "/users", func(c Context) error { r.Add(http.MethodGet, "/users", func(c Context) error {
c.Set("path", "/users") c.Set("path", "/users")
return nil return nil
}) })
r.Add(GET, "/users/:id", func(c Context) error { r.Add(http.MethodGet, "/users/:id", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(http.MethodGet, "/users", c)
c.handler(c) c.handler(c)
assert.Equal(t, "/users", c.Get("path")) assert.Equal(t, "/users", c.Get("path"))
// Route > /users/:id // Route > /users/:id
r.Find(GET, "/users/1", c) r.Find(http.MethodGet, "/users/1", c)
assert.Equal(t, "1", c.Param("id")) assert.Equal(t, "1", c.Param("id"))
// Route > /user // Route > /user
c = e.NewContext(nil, nil).(*context) c = e.NewContext(nil, nil).(*context)
r.Find(GET, "/user", c) r.Find(http.MethodGet, "/user", c)
he := c.handler(c).(*HTTPError) he := c.handler(c).(*HTTPError)
assert.Equal(t, http.StatusNotFound, he.Code) assert.Equal(t, http.StatusNotFound, he.Code)
} }
@ -674,68 +674,68 @@ func TestRouterPriority(t *testing.T) {
r := e.router r := e.router
// Routes // Routes
r.Add(GET, "/users", func(c Context) error { r.Add(http.MethodGet, "/users", func(c Context) error {
c.Set("a", 1) c.Set("a", 1)
return nil return nil
}) })
r.Add(GET, "/users/new", func(c Context) error { r.Add(http.MethodGet, "/users/new", func(c Context) error {
c.Set("b", 2) c.Set("b", 2)
return nil return nil
}) })
r.Add(GET, "/users/:id", func(c Context) error { r.Add(http.MethodGet, "/users/:id", func(c Context) error {
c.Set("c", 3) c.Set("c", 3)
return nil return nil
}) })
r.Add(GET, "/users/dew", func(c Context) error { r.Add(http.MethodGet, "/users/dew", func(c Context) error {
c.Set("d", 4) c.Set("d", 4)
return nil return nil
}) })
r.Add(GET, "/users/:id/files", func(c Context) error { r.Add(http.MethodGet, "/users/:id/files", func(c Context) error {
c.Set("e", 5) c.Set("e", 5)
return nil return nil
}) })
r.Add(GET, "/users/newsee", func(c Context) error { r.Add(http.MethodGet, "/users/newsee", func(c Context) error {
c.Set("f", 6) c.Set("f", 6)
return nil return nil
}) })
r.Add(GET, "/users/*", func(c Context) error { r.Add(http.MethodGet, "/users/*", func(c Context) error {
c.Set("g", 7) c.Set("g", 7)
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(http.MethodGet, "/users", c)
c.handler(c) c.handler(c)
assert.Equal(t, 1, c.Get("a")) assert.Equal(t, 1, c.Get("a"))
// Route > /users/new // Route > /users/new
r.Find(GET, "/users/new", c) r.Find(http.MethodGet, "/users/new", c)
c.handler(c) c.handler(c)
assert.Equal(t, 2, c.Get("b")) assert.Equal(t, 2, c.Get("b"))
// Route > /users/:id // Route > /users/:id
r.Find(GET, "/users/1", c) r.Find(http.MethodGet, "/users/1", c)
c.handler(c) c.handler(c)
assert.Equal(t, 3, c.Get("c")) assert.Equal(t, 3, c.Get("c"))
// Route > /users/dew // Route > /users/dew
r.Find(GET, "/users/dew", c) r.Find(http.MethodGet, "/users/dew", c)
c.handler(c) c.handler(c)
assert.Equal(t, 4, c.Get("d")) assert.Equal(t, 4, c.Get("d"))
// Route > /users/:id/files // Route > /users/:id/files
r.Find(GET, "/users/1/files", c) r.Find(http.MethodGet, "/users/1/files", c)
c.handler(c) c.handler(c)
assert.Equal(t, 5, c.Get("e")) assert.Equal(t, 5, c.Get("e"))
// Route > /users/:id // Route > /users/:id
r.Find(GET, "/users/news", c) r.Find(http.MethodGet, "/users/news", c)
c.handler(c) c.handler(c)
assert.Equal(t, 3, c.Get("c")) assert.Equal(t, 3, c.Get("c"))
// Route > /users/* // Route > /users/*
r.Find(GET, "/users/joe/books", c) r.Find(http.MethodGet, "/users/joe/books", c)
c.handler(c) c.handler(c)
assert.Equal(t, 7, c.Get("g")) assert.Equal(t, 7, c.Get("g"))
assert.Equal(t, "joe/books", c.Param("*")) assert.Equal(t, "joe/books", c.Param("*"))
@ -748,26 +748,26 @@ func TestRouterPriorityNotFound(t *testing.T) {
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
// Add // Add
r.Add(GET, "/a/foo", func(c Context) error { r.Add(http.MethodGet, "/a/foo", func(c Context) error {
c.Set("a", 1) c.Set("a", 1)
return nil return nil
}) })
r.Add(GET, "/a/bar", func(c Context) error { r.Add(http.MethodGet, "/a/bar", func(c Context) error {
c.Set("b", 2) c.Set("b", 2)
return nil return nil
}) })
// Find // Find
r.Find(GET, "/a/foo", c) r.Find(http.MethodGet, "/a/foo", c)
c.handler(c) c.handler(c)
assert.Equal(t, 1, c.Get("a")) assert.Equal(t, 1, c.Get("a"))
r.Find(GET, "/a/bar", c) r.Find(http.MethodGet, "/a/bar", c)
c.handler(c) c.handler(c)
assert.Equal(t, 2, c.Get("b")) assert.Equal(t, 2, c.Get("b"))
c = e.NewContext(nil, nil).(*context) c = e.NewContext(nil, nil).(*context)
r.Find(GET, "/abc/def", c) r.Find(http.MethodGet, "/abc/def", c)
he := c.handler(c).(*HTTPError) he := c.handler(c).(*HTTPError)
assert.Equal(t, http.StatusNotFound, he.Code) assert.Equal(t, http.StatusNotFound, he.Code)
} }
@ -777,30 +777,30 @@ func TestRouterParamNames(t *testing.T) {
r := e.router r := e.router
// Routes // Routes
r.Add(GET, "/users", func(c Context) error { r.Add(http.MethodGet, "/users", func(c Context) error {
c.Set("path", "/users") c.Set("path", "/users")
return nil return nil
}) })
r.Add(GET, "/users/:id", func(c Context) error { r.Add(http.MethodGet, "/users/:id", func(c Context) error {
return nil return nil
}) })
r.Add(GET, "/users/:uid/files/:fid", func(c Context) error { r.Add(http.MethodGet, "/users/:uid/files/:fid", func(c Context) error {
return nil return nil
}) })
c := e.NewContext(nil, nil).(*context) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(http.MethodGet, "/users", c)
c.handler(c) c.handler(c)
assert.Equal(t, "/users", c.Get("path")) assert.Equal(t, "/users", c.Get("path"))
// Route > /users/:id // Route > /users/:id
r.Find(GET, "/users/1", c) r.Find(http.MethodGet, "/users/1", c)
assert.Equal(t, "id", c.pnames[0]) assert.Equal(t, "id", c.pnames[0])
assert.Equal(t, "1", c.Param("id")) assert.Equal(t, "1", c.Param("id"))
// Route > /users/:uid/files/:fid // Route > /users/:uid/files/:fid
r.Find(GET, "/users/1/files/1", c) r.Find(http.MethodGet, "/users/1/files/1", c)
assert.Equal(t, "uid", c.pnames[0]) assert.Equal(t, "uid", c.pnames[0])
assert.Equal(t, "1", c.Param("uid")) assert.Equal(t, "1", c.Param("uid"))
assert.Equal(t, "fid", c.pnames[1]) assert.Equal(t, "fid", c.pnames[1])
@ -813,28 +813,28 @@ func TestRouterStaticDynamicConflict(t *testing.T) {
r := e.router r := e.router
c := e.NewContext(nil, nil) c := e.NewContext(nil, nil)
r.Add(GET, "/dictionary/skills", func(c Context) error { r.Add(http.MethodGet, "/dictionary/skills", func(c Context) error {
c.Set("a", 1) c.Set("a", 1)
return nil return nil
}) })
r.Add(GET, "/dictionary/:name", func(c Context) error { r.Add(http.MethodGet, "/dictionary/:name", func(c Context) error {
c.Set("b", 2) c.Set("b", 2)
return nil return nil
}) })
r.Add(GET, "/server", func(c Context) error { r.Add(http.MethodGet, "/server", func(c Context) error {
c.Set("c", 3) c.Set("c", 3)
return nil return nil
}) })
r.Find(GET, "/dictionary/skills", c) r.Find(http.MethodGet, "/dictionary/skills", c)
c.Handler()(c) c.Handler()(c)
assert.Equal(t, 1, c.Get("a")) assert.Equal(t, 1, c.Get("a"))
c = e.NewContext(nil, nil) c = e.NewContext(nil, nil)
r.Find(GET, "/dictionary/type", c) r.Find(http.MethodGet, "/dictionary/type", c)
c.Handler()(c) c.Handler()(c)
assert.Equal(t, 2, c.Get("b")) assert.Equal(t, 2, c.Get("b"))
c = e.NewContext(nil, nil) c = e.NewContext(nil, nil)
r.Find(GET, "/server", c) r.Find(http.MethodGet, "/server", c)
c.Handler()(c) c.Handler()(c)
assert.Equal(t, 3, c.Get("c")) assert.Equal(t, 3, c.Get("c"))
} }
@ -867,9 +867,9 @@ func TestRouterGitHubAPI(t *testing.T) {
// Issue #729 // Issue #729
func TestRouterParamAlias(t *testing.T) { func TestRouterParamAlias(t *testing.T) {
api := []*Route{ api := []*Route{
{GET, "/users/:userID/following", ""}, {http.MethodGet, "/users/:userID/following", ""},
{GET, "/users/:userID/followedBy", ""}, {http.MethodGet, "/users/:userID/followedBy", ""},
{GET, "/users/:userID/follow", ""}, {http.MethodGet, "/users/:userID/follow", ""},
} }
testRouterAPI(t, api) testRouterAPI(t, api)
} }
@ -877,21 +877,21 @@ func TestRouterParamAlias(t *testing.T) {
// Issue #1052 // Issue #1052
func TestRouterParamOrdering(t *testing.T) { func TestRouterParamOrdering(t *testing.T) {
api := []*Route{ api := []*Route{
{GET, "/:a/:b/:c/:id", ""}, {http.MethodGet, "/:a/:b/:c/:id", ""},
{GET, "/:a/:id", ""}, {http.MethodGet, "/:a/:id", ""},
{GET, "/:a/:e/:id", ""}, {http.MethodGet, "/:a/:e/:id", ""},
} }
testRouterAPI(t, api) testRouterAPI(t, api)
api2 := []*Route{ api2 := []*Route{
{GET, "/:a/:id", ""}, {http.MethodGet, "/:a/:id", ""},
{GET, "/:a/:e/:id", ""}, {http.MethodGet, "/:a/:e/:id", ""},
{GET, "/:a/:b/:c/:id", ""}, {http.MethodGet, "/:a/:b/:c/:id", ""},
} }
testRouterAPI(t, api2) testRouterAPI(t, api2)
api3 := []*Route{ api3 := []*Route{
{GET, "/:a/:b/:c/:id", ""}, {http.MethodGet, "/:a/:b/:c/:id", ""},
{GET, "/:a/:e/:id", ""}, {http.MethodGet, "/:a/:e/:id", ""},
{GET, "/:a/:id", ""}, {http.MethodGet, "/:a/:id", ""},
} }
testRouterAPI(t, api3) testRouterAPI(t, api3)
} }
@ -899,13 +899,13 @@ func TestRouterParamOrdering(t *testing.T) {
// Issue #1139 // Issue #1139
func TestRouterMixedParams(t *testing.T) { func TestRouterMixedParams(t *testing.T) {
api := []*Route{ api := []*Route{
{GET, "/teacher/:tid/room/suggestions", ""}, {http.MethodGet, "/teacher/:tid/room/suggestions", ""},
{GET, "/teacher/:id", ""}, {http.MethodGet, "/teacher/:id", ""},
} }
testRouterAPI(t, api) testRouterAPI(t, api)
api2 := []*Route{ api2 := []*Route{
{GET, "/teacher/:id", ""}, {http.MethodGet, "/teacher/:id", ""},
{GET, "/teacher/:tid/room/suggestions", ""}, {http.MethodGet, "/teacher/:tid/room/suggestions", ""},
} }
testRouterAPI(t, api2) testRouterAPI(t, api2)
} }