| 1 | module main |
| 2 | |
| 3 | import veb |
| 4 | import os |
| 5 | |
| 6 | pub struct User { |
| 7 | pub mut: |
| 8 | name string |
| 9 | id int |
| 10 | } |
| 11 | |
| 12 | // Our context struct must embed `veb.Context`! |
| 13 | pub struct Context { |
| 14 | veb.Context |
| 15 | pub 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 | |
| 22 | pub struct App { |
| 23 | pub: |
| 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 | |
| 31 | fn 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'] |
| 40 | pub fn (app &App) world(mut ctx Context) veb.Result { |
| 41 | return ctx.text('World') |
| 42 | } |
| 43 | |
| 44 | pub fn (app &App) index(mut ctx Context) veb.Result { |
| 45 | return serve_file('html/index.html') |
| 46 | } |
| 47 | |
| 48 | fn serve_file(name string) veb.Result { |
| 49 | content := os.read_file(name) or { panic('Error reading ${name}') } |
| 50 | return ctx.html(content) |
| 51 | } |
| 52 | |