v2 / examples / vwatch / web_server / main.v
70 lines · 62 sloc · 2.0 KB · 4fa8167abbaced0ea99afe662c6ee3a2e2700f40
Raw
1module main
2
3// This example demonstrates how to use `v watch` for veb apps, that use sqlite .db files.
4//
5// Note 1: while developing services, it is useful to also add the `--keep` option of `v watch`,
6// which will restart the app right away, even when it exits on its own.
7//
8// Note 2: veb supports a special live reload mode, where it will make the browser to check for server
9// restarts, and it will trigger a refresh of the current page, right after that is detected.
10//
11// The above means, that to get the most optimal prototyping experience for veb apps, use:
12// `v -d veb_livereload watch --only-watch=*.v,*.html,*.css,*.js --keep run .`
13import os
14import veb
15import db.sqlite
16
17fn mydb() !sqlite.DB {
18 return sqlite.connect(os.resource_abs_path('app.db'))
19}
20
21struct State {
22mut:
23 counter int
24}
25
26pub struct Context {
27 veb.Context
28}
29
30struct App {
31 veb.StaticHandler
32mut:
33 state shared State
34}
35
36pub fn (mut app App) index(mut ctx Context) veb.Result {
37 mut c := 0
38 lock app.state {
39 app.state.counter++
40 c = app.state.counter
41 }
42 visits := app.update_db() or { 0 }
43 return ctx.html('<!doctype html><html><body>
44 <br/>Current request counter, after the server restart: ${c}.
45 <br/>Total stored visits: ${visits}
46 </body></html>')
47}
48
49fn (mut app App) update_db() !int {
50 mut db := mydb()!
51 db.exec('INSERT INTO visits (created_at) VALUES ("")')!
52 visits := db.q_int('SELECT count(*) FROM visits')!
53 db.close()!
54 return visits
55}
56
57fn main() {
58 println('App demonstrating the use of `veb` & `db.sqlite` together.')
59 println('For best prototyping experience, run with:')
60 println('`v -d veb_livereload watch --keep run examples/vwatch/web_server/`')
61 println('')
62 mut db := mydb()!
63 db.exec('CREATE TABLE visits (id integer primary key AUTOINCREMENT, created_at timestamp default current_timestamp);')!
64 db.exec('CREATE TRIGGER INSERT_visits AFTER INSERT ON visits BEGIN
65 UPDATE visits SET created_at = datetime("now", "localtime") WHERE rowid = new.rowid ;
66 END')!
67 db.close()!
68 mut app := &App{}
69 veb.run[App, Context](mut app, 19123)
70}
71