v2 / examples / veb / veb_example.v
80 lines · 66 sloc · 1.52 KB · 3386036f0c244b9e05c2701afd09f8d8fa2b2b9a
Raw
1module main
2
3import veb
4import rand
5
6const port = 8082
7
8struct State {
9mut:
10 cnt int
11}
12
13pub struct App {
14mut:
15 state shared State
16}
17
18struct Context {
19 veb.Context
20}
21
22pub fn (ctx &Context) before_request() {
23 $if trace_before_request ? {
24 eprintln('[veb] before_request: ${ctx.req.method} ${ctx.req.url}')
25 }
26}
27
28@['/users/:user']
29pub fn (mut app App) user_endpoint(mut ctx Context, user string) veb.Result {
30 // pub fn (mut app App) user_endpoint(user string) veb.Result {
31 id := rand.intn(100) or { 0 }
32 return ctx.json({
33 user: id
34 })
35}
36
37pub fn (mut app App) index() veb.Result {
38 println('veb_example.v index()')
39 mut c := 0
40 lock app.state {
41 app.state.cnt++
42 c = app.state.cnt
43 //
44 $if trace_address_of_app_state_cnt ? {
45 dump(ptr_str(app.state.cnt))
46 }
47 }
48 show := true
49 hello := 'Hello world from veb, request number: ${c}'
50 numbers := [1, 2, 3]
51 return $veb.html()
52}
53
54pub fn (mut app App) custom_template(mut ctx Context) veb.Result {
55 return $veb.html('custom.html')
56}
57
58pub fn (mut app App) show_text(mut ctx Context) veb.Result {
59 return ctx.text('Hello world from veb')
60}
61
62pub fn (mut app App) cookie(mut ctx Context) veb.Result {
63 ctx.set_cookie(name: 'cookie', value: 'test')
64 return ctx.text('Response Headers\n${ctx.req.header}')
65}
66
67@[post]
68pub fn (mut app App) post(mut ctx Context) veb.Result {
69 return ctx.text('Post body: ${ctx.req.data}')
70}
71
72fn main() {
73 println('veb example')
74 mut app := &App{}
75 // veb.run(&App{}, port)
76
77 veb.run_at[App, Context](mut app, port: port, family: .ip, timeout_in_seconds: 2) or {
78 panic(err)
79 }
80}
81