1
0
mirror of https://github.com/labstack/echo.git synced 2025-04-23 12:18:53 +02:00

Middleware and handler as closure

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2016-02-17 21:49:31 -08:00
parent c9a62e20b4
commit 88f307bedd
9 changed files with 180 additions and 230 deletions

View File

@ -10,22 +10,22 @@ import (
) )
type ( type (
Static struct { StaticOption struct {
Root string `json:"root"` Root string `json:"root"`
Index string `json:"index"` Index string `json:"index"`
Browse bool `json:"browse"` Browse bool `json:"browse"`
} }
) )
func NewStatic(root string) *Static { func Static(root string, option ...*StaticOption) echo.HandlerFunc {
return &Static{ // Default options
Root: root, opt := &StaticOption{Index: "index.html"}
Index: "index.html", if len(option) > 0 {
opt = option[0]
} }
}
func (s Static) Handle(c echo.Context) error { return func(c echo.Context) error {
fs := http.Dir(s.Root) fs := http.Dir(root)
file := c.P(0) file := c.P(0)
f, err := fs.Open(file) f, err := fs.Open(file)
if err != nil { if err != nil {
@ -46,10 +46,10 @@ func (s Static) Handle(c echo.Context) error {
d := f d := f
// Index file // Index file
file = path.Join(file, s.Index) file = path.Join(file, opt.Index)
f, err = fs.Open(file) f, err = fs.Open(file)
if err != nil { if err != nil {
if s.Browse { if opt.Browse {
dirs, err := d.Readdir(-1) dirs, err := d.Readdir(-1)
if err != nil { if err != nil {
return err return err
@ -84,6 +84,7 @@ func (s Static) Handle(c echo.Context) error {
return nil return nil
// TODO: // TODO:
// http.ServeContent(c.Response(), c.Request(), fi.Name(), fi.ModTime(), f) // http.ServeContent(c.Response(), c.Request(), fi.Name(), fi.ModTime(), f)
}
} }
// Favicon serves the default favicon - GET /favicon.ico. // Favicon serves the default favicon - GET /favicon.ico.

View File

@ -8,10 +8,7 @@ import (
) )
type ( type (
// BasicAuth defines an HTTP basic authentication middleware. BasicAuthOption struct {
BasicAuth struct {
function BasicAuthFunc
priority int
} }
BasicAuthFunc func(string, string) bool BasicAuthFunc func(string, string) bool
@ -21,23 +18,12 @@ const (
basic = "Basic" basic = "Basic"
) )
func NewBasicAuth(fn BasicAuthFunc) *BasicAuth { // BasicAuth returns an HTTP basic authentication middleware.
return &BasicAuth{function: fn}
}
func (ba *BasicAuth) SetPriority(p int) {
ba.priority = p
}
func (ba *BasicAuth) Priority() int {
return ba.priority
}
// Handle validates credentials using `AuthFunc`
// //
// For valid credentials it calls the next handler. // For valid credentials it calls the next handler.
// For invalid credentials, it sends "401 - Unauthorized" response. // For invalid credentials, it sends "401 - Unauthorized" response.
func (ba *BasicAuth) Handle(h echo.Handler) echo.Handler { func BasicAuth(fn BasicAuthFunc, option ...*BasicAuthOption) echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error { return echo.HandlerFunc(func(c echo.Context) error {
// Skip WebSocket // Skip WebSocket
if (c.Request().Header().Get(echo.Upgrade)) == echo.WebSocket { if (c.Request().Header().Get(echo.Upgrade)) == echo.WebSocket {
@ -54,7 +40,7 @@ func (ba *BasicAuth) Handle(h echo.Handler) echo.Handler {
for i := 0; i < len(cred); i++ { for i := 0; i < len(cred); i++ {
if cred[i] == ':' { if cred[i] == ':' {
// Verify credentials // Verify credentials
if ba.function(cred[:i], cred[i+1:]) { if fn(cred[:i], cred[i+1:]) {
return nil return nil
} }
} }
@ -64,4 +50,5 @@ func (ba *BasicAuth) Handle(h echo.Handler) echo.Handler {
c.Response().Header().Set(echo.WWWAuthenticate, basic+" realm=Restricted") c.Response().Header().Set(echo.WWWAuthenticate, basic+" realm=Restricted")
return echo.NewHTTPError(http.StatusUnauthorized) return echo.NewHTTPError(http.StatusUnauthorized)
}) })
}
} }

View File

@ -21,7 +21,7 @@ func TestBasicAuth(t *testing.T) {
} }
return false return false
} }
h := NewBasicAuth(fn).Handle(echo.HandlerFunc(func(c echo.Context) error { h := BasicAuth(fn)(echo.HandlerFunc(func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
})) }))

View File

@ -15,9 +15,8 @@ import (
) )
type ( type (
Gzip struct { GzipOption struct {
level int level int
priority int
} }
gzipWriter struct { gzipWriter struct {
@ -26,25 +25,10 @@ type (
} }
) )
func NewGzip() *Gzip {
return &Gzip{}
}
func (g *Gzip) SetLevel(l int) {
g.level = l
}
func (g *Gzip) SetPriority(p int) {
g.priority = p
}
func (g *Gzip) Priority() int {
return g.priority
}
// Gzip returns a middleware which compresses HTTP response using gzip compression // Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme. // scheme.
func (*Gzip) Handle(h echo.Handler) echo.Handler { func Gzip(option ...*GzipOption) echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
scheme := "gzip" scheme := "gzip"
return echo.HandlerFunc(func(c echo.Context) error { return echo.HandlerFunc(func(c echo.Context) error {
c.Response().Header().Add(echo.Vary, echo.AcceptEncoding) c.Response().Header().Add(echo.Vary, echo.AcceptEncoding)
@ -64,6 +48,7 @@ func (*Gzip) Handle(h echo.Handler) echo.Handler {
} }
return nil return nil
}) })
}
} }
func (w gzipWriter) Write(b []byte) (int, error) { func (w gzipWriter) Write(b []byte) (int, error) {

View File

@ -36,7 +36,7 @@ func TestGzip(t *testing.T) {
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := echo.NewContext(req, rec, e) c := echo.NewContext(req, rec, e)
// Skip if no Accept-Encoding header // Skip if no Accept-Encoding header
h := NewGzip().Handle(echo.HandlerFunc(func(c echo.Context) error { h := Gzip()(echo.HandlerFunc(func(c echo.Context) error {
c.Response().Write([]byte("test")) // For Content-Type sniffing c.Response().Write([]byte("test")) // For Content-Type sniffing
return nil return nil
})) }))

View File

@ -9,24 +9,12 @@ import (
) )
type ( type (
Log struct { LogOption struct {
priority int
} }
) )
func NewLog() *Log { func Log(option ...*LogOption) echo.MiddlewareFunc {
return &Log{} return func(h echo.Handler) echo.Handler {
}
func (l *Log) SetPriority(p int) {
l.priority = p
}
func (l *Log) Priority() int {
return l.priority
}
func (*Log) Handle(h echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error { return echo.HandlerFunc(func(c echo.Context) error {
req := c.Request() req := c.Request()
res := c.Response() res := c.Response()
@ -67,4 +55,5 @@ func (*Log) Handle(h echo.Handler) echo.Handler {
logger.Infof("%s %s %s %s %s %d", remoteAddr, method, path, code, stop.Sub(start), size) logger.Infof("%s %s %s %s %s %d", remoteAddr, method, path, code, stop.Sub(start), size)
return nil return nil
}) })
}
} }

View File

@ -18,8 +18,7 @@ func TestLog(t *testing.T) {
req := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := echo.NewContext(req, rec, e) c := echo.NewContext(req, rec, e)
l := NewLog() h := Log()(echo.HandlerFunc(func(c echo.Context) error {
h := l.Handle(echo.HandlerFunc(func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
})) }))
@ -29,7 +28,7 @@ func TestLog(t *testing.T) {
// Status 3xx // Status 3xx
rec = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = echo.NewContext(req, rec, e) c = echo.NewContext(req, rec, e)
h = l.Handle(echo.HandlerFunc(func(c echo.Context) error { h = Log()(echo.HandlerFunc(func(c echo.Context) error {
return c.String(http.StatusTemporaryRedirect, "test") return c.String(http.StatusTemporaryRedirect, "test")
})) }))
h.Handle(c) h.Handle(c)
@ -37,7 +36,7 @@ func TestLog(t *testing.T) {
// Status 4xx // Status 4xx
rec = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = echo.NewContext(req, rec, e) c = echo.NewContext(req, rec, e)
h = l.Handle(echo.HandlerFunc(func(c echo.Context) error { h = Log()(echo.HandlerFunc(func(c echo.Context) error {
return c.String(http.StatusNotFound, "test") return c.String(http.StatusNotFound, "test")
})) }))
h.Handle(c) h.Handle(c)
@ -46,7 +45,7 @@ func TestLog(t *testing.T) {
req = test.NewRequest(echo.GET, "", nil) req = test.NewRequest(echo.GET, "", nil)
rec = test.NewResponseRecorder() rec = test.NewResponseRecorder()
c = echo.NewContext(req, rec, e) c = echo.NewContext(req, rec, e)
h = l.Handle(echo.HandlerFunc(func(c echo.Context) error { h = Log()(echo.HandlerFunc(func(c echo.Context) error {
return errors.New("error") return errors.New("error")
})) }))
h.Handle(c) h.Handle(c)
@ -60,7 +59,7 @@ func TestLogIPAddress(t *testing.T) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
e.Logger().(*log.Logger).SetOutput(buf) e.Logger().(*log.Logger).SetOutput(buf)
ip := "127.0.0.1" ip := "127.0.0.1"
h := NewLog().Handle(echo.HandlerFunc(func(c echo.Context) error { h := Log()(echo.HandlerFunc(func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
})) }))

View File

@ -9,26 +9,14 @@ import (
) )
type ( type (
Recover struct { RecoverOption struct {
priority int
} }
) )
func NewRecover() *Recover {
return &Recover{}
}
func (r *Recover) SetPriority(p int) {
r.priority = p
}
func (r *Recover) Priority() int {
return r.priority
}
// Recover returns a middleware which recovers from panics anywhere in the chain // Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler. // and handles the control to the centralized HTTPErrorHandler.
func (*Recover) Handle(h echo.Handler) echo.Handler { func Recover(option ...*RecoverOption) echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
// TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace` // TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace`
return echo.HandlerFunc(func(c echo.Context) error { return echo.HandlerFunc(func(c echo.Context) error {
defer func() { defer func() {
@ -41,4 +29,5 @@ func (*Recover) Handle(h echo.Handler) echo.Handler {
}() }()
return h.Handle(c) return h.Handle(c)
}) })
}
} }

View File

@ -15,7 +15,7 @@ func TestRecover(t *testing.T) {
req := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
rec := test.NewResponseRecorder() rec := test.NewResponseRecorder()
c := echo.NewContext(req, rec, e) c := echo.NewContext(req, rec, e)
h := NewRecover().Handle(echo.HandlerFunc(func(c echo.Context) error { h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
panic("test") panic("test")
})) }))
h.Handle(c) h.Handle(c)