1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

vweb: init_once() => init_server(); init() => before_request()

This commit is contained in:
Alexander Medvednikov
2021-04-15 06:27:24 +03:00
parent 3a134acc5a
commit a18f85c8cd
9 changed files with 26 additions and 24 deletions

View File

@ -73,11 +73,6 @@ pub fn (mut app App) index() vweb.Result {
return app.text('Hello world from vweb!')
}
pub fn (app &App) init() {
}
pub fn (app &App) init_once() {
}
```
Run it with
@ -228,10 +223,10 @@ mut:
Modify the `init_once()` method we created earlier to connect to a database:
Add the `init_server()` method where we'll connect to a database:
```v oksyntax
pub fn (mut app App) init_once() {
pub fn (mut app App) init_server() {
db := sqlite.connect(':memory:') or { panic(err) }
db.exec('create table `Article` (id integer primary key, title text default "", text text default "")')
db.exec('insert into Article (title, text) values ("Hello, world!", "V is great.")')
@ -240,7 +235,7 @@ pub fn (mut app App) init_once() {
}
```
Code in the `init_once()` function is run only once during app's startup, so we are going
Code in the `init_server()` function is run only once during app's startup, so we are going
to have one DB connection for all requests.
Create a new file `article.v`:

View File

@ -8,7 +8,8 @@ import json
struct App {
vweb.Context
mut:
db sqlite.DB
db sqlite.DB [server_var]
user_id string
}
fn main() {
@ -31,7 +32,7 @@ pub fn (app &App) index() vweb.Result {
return $vweb.html()
}
pub fn (mut app App) init_once() {
pub fn (mut app App) init_server() {
app.db = sqlite.connect('blog.db') or { panic(err) }
app.db.create_table('article', [
'id integer primary key',
@ -40,7 +41,8 @@ pub fn (mut app App) init_once() {
])
}
pub fn (mut app App) init() {
pub fn (mut app App) before_request() {
app.user_id = app.get_cookie('id') or { '0' }
}
pub fn (mut app App) new() vweb.Result {

View File

@ -3,6 +3,7 @@
<title>V Blog</title>
</header>
<body>
user id = @app.user_id <br>
@for article in articles
<div>
<b>@article.title</b> <br>