In this example you'll just see one use case of .WrapRouter. You can use the .WrapRouter to add custom logic when or when not the router should be executed in order to execute the registered routes' handlers.
()
| 11 | // You can use the .WrapRouter to add custom logic when or when not the router should |
| 12 | // be executed in order to execute the registered routes' handlers. |
| 13 | func newApp() *iris.Application { |
| 14 | app := iris.New() |
| 15 | |
| 16 | app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) { |
| 17 | ctx.HTML("<b>Resource Not found</b>") |
| 18 | }) |
| 19 | |
| 20 | app.Get("/profile/{username}", func(ctx iris.Context) { |
| 21 | ctx.Writef("Hello %s", ctx.Params().Get("username")) |
| 22 | }) |
| 23 | |
| 24 | app.HandleDir("/", iris.Dir("./public")) |
| 25 | |
| 26 | myOtherHandler := func(ctx iris.Context) { |
| 27 | ctx.Writef("inside a handler which is fired manually by our custom router wrapper") |
| 28 | } |
| 29 | |
| 30 | // wrap the router with a native net/http handler. |
| 31 | // if url does not contain any "." (i.e: .css, .js...) |
| 32 | // (depends on the app , you may need to add more file-server exceptions), |
| 33 | // then the handler will execute the router that is responsible for the |
| 34 | // registered routes (look "/" and "/profile/{username}") |
| 35 | // if not then it will serve the files based on the root "/" path. |
| 36 | app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) { |
| 37 | path := r.URL.Path |
| 38 | |
| 39 | if strings.HasPrefix(path, "/other") { |
| 40 | // acquire and release a context in order to use it to execute |
| 41 | // our custom handler |
| 42 | // remember: we use net/http.Handler because here we are in the "low-level", before the router itself. |
| 43 | ctx := app.ContextPool.Acquire(w, r) |
| 44 | myOtherHandler(ctx) |
| 45 | app.ContextPool.Release(ctx) |
| 46 | return |
| 47 | } |
| 48 | |
| 49 | router.ServeHTTP(w, r) // else continue serving routes as usual. |
| 50 | }) |
| 51 | |
| 52 | return app |
| 53 | } |
| 54 | |
| 55 | func main() { |
| 56 | app := newApp() |
searching dependent graphs…