MCPcopy Create free account
hub / github.com/kataras/iris / newApp

Function newApp

_examples/routing/custom-wrapper/main.go:13–53  ·  view source on GitHub ↗

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.

()

Source from the content-addressed store, hash-verified

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.
13func 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
55func main() {
56 app := newApp()

Callers 2

TestCustomWrapperFunction · 0.70
mainFunction · 0.70

Calls 11

NewMethod · 0.80
WritefMethod · 0.80
ParamsMethod · 0.80
WrapRouterMethod · 0.80
OnErrorCodeMethod · 0.65
GetMethod · 0.65
HandleDirMethod · 0.65
AcquireMethod · 0.65
ReleaseMethod · 0.65
ServeHTTPMethod · 0.65
HTMLMethod · 0.45

Tested by 1

TestCustomWrapperFunction · 0.56

Used in the wild real call sites across dependent graphs

searching dependent graphs…