()
| 5 | ) |
| 6 | |
| 7 | func newApp() *iris.Application { |
| 8 | app := iris.New() |
| 9 | v1 := app.Party("/api/v1") |
| 10 | |
| 11 | myFilter := func(ctx iris.Context) bool { |
| 12 | // don't do that on production, use session or/and database calls and etc. |
| 13 | ok, _ := ctx.URLParamBool("admin") |
| 14 | return ok |
| 15 | } |
| 16 | |
| 17 | onlyWhenFilter1 := func(ctx iris.Context) { |
| 18 | ctx.Application().Logger().Infof("admin: %#+v", ctx.URLParams()) |
| 19 | ctx.Writef("<title>Admin</title>\n") |
| 20 | ctx.Next() |
| 21 | } |
| 22 | |
| 23 | onlyWhenFilter2 := func(ctx iris.Context) { |
| 24 | // You can always use the per-request storage |
| 25 | // to perform actions like this ofc. |
| 26 | // |
| 27 | // this handler: ctx.Values().Set("is_admin", true) |
| 28 | // next handler: isAdmin := ctx.Values().GetBoolDefault("is_admin", false) |
| 29 | // |
| 30 | // but, let's simplify it: |
| 31 | ctx.HTML("<h1>Hello Admin</h1><br>") |
| 32 | ctx.Next() |
| 33 | } |
| 34 | |
| 35 | // HERE: |
| 36 | // It can be registered anywhere, as a middleware. |
| 37 | // It will fire the `onlyWhenFilter1` and `onlyWhenFilter2` as middlewares (with ctx.Next()) |
| 38 | // if myFilter pass otherwise it will just continue the handler chain with ctx.Next() by ignoring |
| 39 | // the `onlyWhenFilter1` and `onlyWhenFilter2`. |
| 40 | myMiddleware := iris.NewConditionalHandler(myFilter, onlyWhenFilter1, onlyWhenFilter2) |
| 41 | |
| 42 | v1UsersRouter := v1.Party("/users", myMiddleware) |
| 43 | v1UsersRouter.Get("/", func(ctx iris.Context) { |
| 44 | ctx.HTML("requested: <b>/api/v1/users</b>") |
| 45 | }) |
| 46 | |
| 47 | return app |
| 48 | } |
| 49 | |
| 50 | func main() { |
| 51 | app := newApp() |
searching dependent graphs…