v2 / examples / veb / middleware / using_middleware.v
95 lines · 75 sloc · 1.91 KB · ce76dc87648ce6b113899ae536804151670989b7
Raw
1module main
2
3import veb
4
5// for another example see vlib/veb/tests/middleware_test.v
6const http_port = 8080
7
8pub struct Context {
9 veb.Context
10mut:
11 is_authenticated bool
12}
13
14struct App {
15 veb.Middleware[Context]
16}
17
18fn main() {
19 mut app := &App{}
20
21 // chaining is allowed, middleware will be evaluated in order
22 app.Middleware.use(handler: other_func1)
23 app.Middleware.use(handler: other_func2)
24
25 // route-specific middleware
26 app.Middleware.route_use('/admin/:path...', handler: check_auth)
27 app.Middleware.route_use('/early', handler: middleware_early)
28
29 veb.run[App, Context](mut app, http_port)
30}
31
32@['/']
33pub fn (app &App) index(mut ctx Context) veb.Result {
34 println('Index page')
35 title := 'Home Page'
36
37 content := $tmpl('templates/index.html')
38 base := $tmpl('templates/base.html')
39 return ctx.html(base)
40}
41
42@['/admin/secrets']
43pub fn (app &App) secrets(mut ctx Context) veb.Result {
44 println('Secrets page')
45 title := 'Secret Admin Page'
46
47 content := $tmpl('templates/secret.html')
48 base := $tmpl('templates/base.html')
49 return ctx.html(base)
50}
51
52@['/admin/:sub']
53pub fn (app &App) dynamic(mut ctx Context, sub string) veb.Result {
54 println('Dynamic page')
55 title := 'Secret dynamic'
56
57 content := sub
58 base := $tmpl('templates/base.html')
59 return ctx.html(base)
60}
61
62@['/early']
63pub fn (app &App) early(mut ctx Context) veb.Result {
64 println('Early page')
65 title := 'Early Exit'
66
67 content := $tmpl('templates/early.html')
68 base := $tmpl('templates/base.html')
69 return ctx.html(base)
70}
71
72fn other_func1(mut _ Context) bool {
73 println('1')
74 return true
75}
76
77fn other_func2(mut _ Context) bool {
78 println('2')
79 return true
80}
81
82fn check_auth(mut ctx Context) bool {
83 println('3')
84 if ctx.is_authenticated == false {
85 ctx.redirect('/')
86 }
87 return ctx.is_authenticated
88}
89
90fn middleware_early(mut ctx Context) bool {
91 println('4')
92 ctx.text(':(')
93 // returns false, so the middleware propagation is stopped and the user will see the text ":("
94 return false
95}
96