diff --git a/app.go b/app.go index 77b0f72..823af3c 100644 --- a/app.go +++ b/app.go @@ -139,6 +139,10 @@ func (a *App) addRoute(method, path string, handlers ...HandlerFunc) { } func (a *App) handleHTTPRequest(c *Ctx) { + var ( + err error + ) + httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false @@ -166,8 +170,11 @@ func (a *App) handleHTTPRequest(c *Ctx) { if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath - // todo - c.Next() + + if err = c.Next(); err != nil { + serveError(c, errorHandler) + } + c.writermem.WriteHeaderNow() return } @@ -210,8 +217,8 @@ func (a *App) handleHTTPRequest(c *Ctx) { serveError(c, a.config.NotFoundHandler) } -func errorHandler(c *Ctx) { - _ = c.Status(500).SendString(_500) +func errorHandler(c *Ctx) error { + return c.Status(500).SendString(_500) } func serveError(c *Ctx, handler HandlerFunc) { diff --git a/ctx.go b/ctx.go index 67d539b..3af1133 100644 --- a/ctx.go +++ b/ctx.go @@ -110,18 +110,21 @@ func (c *Ctx) Cookies(key string, defaultValue ...string) string { func (c *Ctx) Next() error { c.index++ - var err error + var ( + err error + handler = c.handlers[c.index] + ) - for c.index < len(c.handlers) { - if c.handlers[c.index] != nil { - if err = c.handlers[c.index](c); err != nil { - return err - } + //for c.index < len(c.handlers) { + if handler != nil { + if err = handler(c); err != nil { + return err } - - c.index++ } + c.index++ + //} + return nil } diff --git a/xtest/midd2/main.go b/xtest/midd2/main.go new file mode 100644 index 0000000..b744d0c --- /dev/null +++ b/xtest/midd2/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "errors" + "github.com/loveuer/nf" + "github.com/loveuer/nf/nft/resp" + "log" +) + +func main() { + app := nf.New() + + api := app.Group("/api") + + api.Get("/hello", + auth(), + func(c *nf.Ctx) error { + return resp.Resp403(c, errors.New("in hello")) + }, + ) + + log.Fatal(app.Run(":80")) +} + +func auth() nf.HandlerFunc { + return func(c *nf.Ctx) error { + token := c.Query("token") + if token != "zyp" { + return resp.Resp401(c, errors.New("no auth")) + } + + return c.Next() + } +}