1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Dropped support for func(http.Handler) http.Handler middleware

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2015-04-19 16:00:23 -07:00
parent 54824fc22f
commit 3eeea660fa
10 changed files with 52 additions and 156 deletions

View File

@ -9,7 +9,6 @@ Echo is a fast HTTP router (zero memory allocation) and micro web framework in G
- `func(*echo.Context)`
- `func(*echo.Context) error`
- `func(echo.HandlerFunc) echo.HandlerFunc`
- `func(http.Handler) http.Handler`
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
@ -68,6 +67,7 @@ BenchmarkZeus_GithubAll 2000 752907 ns/op 300688 B/op 2648 all
## Examples
[labstack/echo/example](https://github.com/labstack/echo/tree/master/examples)
> Hello, World!
```go
@ -95,7 +95,7 @@ func main() {
e.Get("/", hello)
// Start server
e.Run(":8080")
e.Run(":4444")
}
```
## License

View File

@ -79,8 +79,10 @@ func (c *Context) NoContent(code int) error {
return nil
}
// func (c *Context) File(code int, file, name string) {
// }
// Error invokes the registered HTTP error handler.
func (c *Context) Error(err error) {
c.echo.httpErrorHandler(err, c)
}
// Get retrieves data from the context.
func (c *Context) Get(key string) interface{} {

25
echo.go
View File

@ -108,7 +108,7 @@ func New() (e *Echo) {
e.HTTPErrorHandler(func(err error, c *Context) {
if err != nil {
// TODO: Warning
log.Println(color.Yellow("echo: HTTP error handler not registered"))
log.Printf("echo: %s", color.Yellow("HTTP error handler not registered"))
http.Error(c.Response, err.Error(), http.StatusInternalServerError)
}
})
@ -125,10 +125,6 @@ func New() (e *Echo) {
return
}
// NOP
func (h HandlerFunc) ServeHTTP(http.ResponseWriter, *http.Request) {
}
// Group creates a new sub router with prefix and inherits all properties from
// the parent. Passing middleware overrides parent middleware.
func (e *Echo) Group(pfx string, m ...Middleware) *Echo {
@ -257,12 +253,12 @@ func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
c.reset(w, r, e)
// Middleware
// Chain middleware with handler in the end
for i := len(e.middleware) - 1; i >= 0; i-- {
h = e.middleware[i](h)
}
// Handler
// Execute chain
if err := h(c); err != nil {
e.httpErrorHandler(err, c)
}
@ -270,23 +266,23 @@ func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.pool.Put(c)
}
// Run a server
// Run runs a server.
func (e *Echo) Run(addr string) {
log.Fatal(http.ListenAndServe(addr, e))
}
// RunTLS a server
// RunTLS runs a server with TLS configuration.
func (e *Echo) RunTLS(addr, certFile, keyFile string) {
log.Fatal(http.ListenAndServeTLS(addr, certFile, keyFile, e))
}
// RunServer runs a custom server
// RunServer runs a custom server.
func (e *Echo) RunServer(server *http.Server) {
server.Handler = e
log.Fatal(server.ListenAndServe())
}
// RunTLSServer runs a custom server with TLS configuration
// RunTLSServer runs a custom server with TLS configuration.
func (e *Echo) RunTLSServer(server *http.Server, certFile, keyFile string) {
server.Handler = e
log.Fatal(server.ListenAndServeTLS(certFile, keyFile))
@ -313,13 +309,6 @@ func wrapM(m Middleware) MiddlewareFunc {
}
case func(HandlerFunc) HandlerFunc:
return m
case func(http.Handler) http.Handler:
return func(h HandlerFunc) HandlerFunc {
return func(c *Context) error {
m(h).ServeHTTP(c.Response, c.Request)
return h(c)
}
}
case http.Handler, http.HandlerFunc:
return func(h HandlerFunc) HandlerFunc {
return func(c *Context) error {

View File

@ -84,21 +84,21 @@ func TestEchoMiddleware(t *testing.T) {
})))
// func(http.Handler) http.Handler
e.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b.WriteString("f")
h.ServeHTTP(w, r)
})
})
// e.Use(func(h http.Handler) http.Handler {
// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// b.WriteString("f")
// h.ServeHTTP(w, r)
// })
// })
// func(http.ResponseWriter, *http.Request)
e.Use(func(w http.ResponseWriter, r *http.Request) {
b.WriteString("g")
b.WriteString("f")
})
// func(http.ResponseWriter, *http.Request) error
e.Use(func(w http.ResponseWriter, r *http.Request) error {
b.WriteString("h")
b.WriteString("g")
return nil
})
@ -110,8 +110,8 @@ func TestEchoMiddleware(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest(GET, "/hello", nil)
e.ServeHTTP(w, r)
if b.String() != "abcdefgh" {
t.Errorf("buffer should be abcdefgh, found %s", b.String())
if b.String() != "abcdefg" {
t.Errorf("buffer should be abcdefg, found %s", b.String())
}
if w.Body.String() != "world" {
t.Error("body should be world")

View File

@ -5,7 +5,6 @@ import (
"strconv"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
type (
@ -61,7 +60,7 @@ func main() {
e := echo.New()
// Middleware
e.Use(mw.Logger)
e.Use(echo.Logger)
// Routes
e.Post("/users", createUser)

View File

@ -7,9 +7,6 @@ import (
"html/template"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
"github.com/rs/cors"
"github.com/thoas/stats"
)
type (
@ -37,47 +34,28 @@ func welcome(c *echo.Context) {
c.Render(http.StatusOK, "welcome", "Joe")
}
func createUser(c *echo.Context) {
func createUser(c *echo.Context) error {
u := new(user)
if err := c.Bind(u); err == nil {
users[u.ID] = *u
if err := c.JSON(http.StatusCreated, u); err == nil {
// Do something!
}
return
if err := c.Bind(u); err != nil {
return err
}
http.Error(c.Response, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
users[u.ID] = *u
return c.JSON(http.StatusCreated, u)
}
func getUsers(c *echo.Context) {
c.JSON(http.StatusOK, users)
func getUsers(c *echo.Context) error {
return c.JSON(http.StatusOK, users)
}
func getUser(c *echo.Context) {
c.JSON(http.StatusOK, users[c.P(0)])
func getUser(c *echo.Context) error {
return c.JSON(http.StatusOK, users[c.P(0)])
}
func main() {
e := echo.New()
//---------------------
// Built-in middleware
//---------------------
e.Use(mw.Logger)
//------------------------
// Third-party middleware
//------------------------
// https://github.com/rs/cors
e.Use(cors.Default().Handler)
// https://github.com/thoas/stats
s := stats.New()
e.Use(s.Handler)
// Route
e.Get("/stats", func(c *echo.Context) {
c.JSON(200, s.Data())
})
// Middleware
e.Use(echo.Logger)
// Serve index file
e.Index("public/index.html")
@ -92,9 +70,9 @@ func main() {
e.Get("/users", getUsers)
e.Get("/users/:id", getUser)
//***************//
// Templates //
//***************//
//-----------
// Templates
//-----------
t := &Template{
// Cached templates
templates: template.Must(template.ParseFiles("public/views/welcome.html")),
@ -102,9 +80,10 @@ func main() {
e.Renderer(t)
e.Get("/welcome", welcome)
//***********//
// Group //
//***********//
//-------
// Group
//-------
// Group with parent middleware
a := e.Group("/admin")
a.Use(func(c *echo.Context) {
@ -123,7 +102,7 @@ func main() {
})
// Start server
e.Run(":8080")
e.Run(":4444")
}
func init() {

View File

@ -1,24 +1,23 @@
package middleware
package echo
import (
"log"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/color"
"labstack.com/gommon/color"
)
func Logger(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
func Logger(h HandlerFunc) HandlerFunc {
return func(c *Context) error {
start := time.Now()
if err := h(c); err != nil {
return err
c.Error(err)
}
end := time.Now()
col := color.Green
m := c.Request.Method
p := c.Request.URL.Path
n := c.Response.Status()
col := color.Green
switch {
case n >= 500:

View File

@ -1,70 +0,0 @@
package middleware
//
// import (
// "encoding/base64"
// "errors"
// "strings"
//
// "github.com/dgrijalva/jwt-go"
// "github.com/labstack/echo"
// )
//
// type (
// BasicAuthFunc func(string, string) bool
// AuthorizedHandler echo.HandlerFunc
// UnauthorizedHandler func(*echo.Context, error)
// JwtKeyFunc func(string) ([]byte, error)
// Claims map[string]interface{}
// )
//
// var (
// ErrBasicAuth = errors.New("echo: basic auth error")
// ErrJwtAuth = errors.New("echo: jwt auth error")
// )
//
// func BasicAuth(ah AuthorizedHandler, uah UnauthorizedHandler, fn BasicAuthFunc) echo.HandlerFunc {
// return func(c *echo.Context) {
// auth := strings.Fields(c.Request.Header.Get("Authorization"))
// if len(auth) == 2 {
// scheme := auth[0]
// s, err := base64.StdEncoding.DecodeString(auth[1])
// if err != nil {
// uah(c, err)
// return
// }
// cred := strings.Split(string(s), ":")
// if scheme == "Basic" && len(cred) == 2 {
// if ok := fn(cred[0], cred[1]); ok {
// ah(c)
// return
// }
// }
// }
// uah(c, ErrBasicAuth)
// }
// }
//
// func JwtAuth(ah AuthorizedHandler, uah UnauthorizedHandler, fn JwtKeyFunc) echo.HandlerFunc {
// return func(c *echo.Context) {
// auth := strings.Fields(c.Request.Header.Get("Authorization"))
// if len(auth) == 2 {
// t, err := jwt.Parse(auth[1], func(token *jwt.Token) (interface{}, error) {
// if kid := token.Header["kid"]; kid != nil {
// return fn(kid.(string))
// }
// return fn("")
// })
// if t.Valid {
// c.Set("claims", Claims(t.Claims))
// ah(c)
// // c.Next()
// } else {
// // TODO: capture errors
// uah(c, err)
// }
// return
// }
// uah(c, ErrJwtAuth)
// }
// }

View File

@ -23,7 +23,7 @@ func (r *response) Header() http.Header {
func (r *response) WriteHeader(n int) {
if r.committed {
// TODO: Warning
log.Println(color.Yellow("echo: response already committed"))
log.Printf("echo: %s", color.Yellow("echo: response already committed"))
return
}
r.status = n

View File

@ -9,7 +9,6 @@ Echo is a fast HTTP router (zero memory allocation) and micro web framework in G
- `func(*echo.Context)`
- `func(*echo.Context) error`
- `func(echo.HandlerFunc) echo.HandlerFunc`
- `func(http.Handler) http.Handler`
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
@ -71,7 +70,7 @@ func main() {
```curl -X POST -H "Content-Type: application/json" -d '{"name":"Joe"}' http://localhost:4444/users```
- Get user
```curl http://localhost:4444/users/1```
- Update user: Change the user name to Sid
- Update user: Change user's name to Sid
```curl -X PATCH -H "Content-Type: application/json" -d '{"name":"Sid"}' http://localhost:4444/users/1```
- Delete user
```curl -X DELETE http://localhost:4444/users/1```
@ -85,7 +84,6 @@ import (
"strconv"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
type (
@ -141,7 +139,7 @@ func main() {
e := echo.New()
// Middleware
e.Use(mw.Logger)
e.Use(echo.Logger)
// Routes
e.Post("/users", createUser)