v2 / vlib / v / checker / tests / veb_ctx_on_fn_err.vv
51 lines · 42 sloc · 1.05 KB · 99635cfba922475d7e639680c1cd90149608a896
Raw
1module main
2
3import veb
4import os
5
6pub struct User {
7pub mut:
8 name string
9 id int
10}
11
12// Our context struct must embed `veb.Context`!
13pub struct Context {
14 veb.Context
15pub mut:
16 // In the context struct we store data that could be different
17 // for each request. Like a User struct or a session id
18 user User
19 session_id string
20}
21
22pub struct App {
23pub:
24 // In the app struct we store data that should be accessible by all endpoints.
25 // For example, a database or configuration values.
26 secret_key string
27}
28
29// This is how endpoints are defined in veb. This is the index route
30
31fn main() {
32 mut app := &App{
33 secret_key: 'secret'
34 }
35 // Pass the App and context type and start the web server on port 8080
36 veb.run[App, Context](mut app, 8080)
37}
38
39@['/foo']
40pub fn (app &App) world(mut ctx Context) veb.Result {
41 return ctx.text('World')
42}
43
44pub fn (app &App) index(mut ctx Context) veb.Result {
45 return serve_file('html/index.html')
46}
47
48fn serve_file(name string) veb.Result {
49 content := os.read_file(name) or { panic('Error reading ${name}') }
50 return ctx.html(content)
51}
52