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

tutorials: web blog fixes

This commit is contained in:
Alexander Medvednikov 2020-06-30 21:04:00 +02:00
parent 7df6984261
commit 34ddc9240e
3 changed files with 25 additions and 27 deletions

View File

@ -7,9 +7,9 @@ struct Article {
} }
pub fn (app &App) find_all_articles() []Article { pub fn (app &App) find_all_articles() []Article {
db := app.db return sql app.db {
articles := db.select from Article select from Article
return articles }
} }

View File

@ -2,17 +2,17 @@ module main
import vweb import vweb
import time import time
import pg import sqlite
import json import json
pub struct App { struct App {
mut: pub mut:
vweb vweb.Context vweb vweb.Context
db pg.DB db sqlite.DB
} }
fn main() { fn main() {
vweb.run<App>(8080) vweb.run<App>(8081)
} }
fn (mut app App) index_text() { fn (mut app App) index_text() {
@ -26,42 +26,39 @@ fn (app &App) index_html() {
} }
*/ */
fn (app &App) index() { fn (app &App) index() vweb.Result {
articles := app.find_all_articles() articles := app.find_all_articles()
$vweb.html() return $vweb.html()
} }
pub fn (mut app App) init() { pub fn (mut app App) init_once() {
db := pg.connect(pg.Config{ db := sqlite.connect(':memory:') or { panic(err) }
host: '127.0.0.1'
dbname: 'blog'
user: 'alex'
}) or { panic(err) }
app.db = db app.db = db
} }
pub fn (mut app App) new() { pub fn (mut app App) init() {
$vweb.html()
} }
pub fn (mut app App) reset() { pub fn (mut app App) new() vweb.Result{
return $vweb.html()
} }
pub fn (mut app App) new_article() { pub fn (mut app App) new_article() vweb.Result {
title := app.vweb.form['title'] title := app.vweb.form['title']
text := app.vweb.form['text'] text := app.vweb.form['text']
if title == '' || text == '' { if title == '' || text == '' {
app.vweb.text('Empty text/titile') app.vweb.text('Empty text/titile')
return return vweb.Result{}
} }
article := Article{ article := Article{
title: title title: title
text: text text: text
} }
println(article) println(article)
db := app.db sql app.db {
db.insert(article) insert article into Article
app.vweb.redirect('/article/') }
return app.vweb.redirect('/article/')
} }
pub fn (mut app App) articles() { pub fn (mut app App) articles() {

View File

@ -92,10 +92,11 @@ pub fn (mut ctx Context) ok(s string) Result {
return Result{} return Result{}
} }
pub fn (mut ctx Context) redirect(url string) { pub fn (mut ctx Context) redirect(url string) Result {
if ctx.done { return } if ctx.done { return Result{} }
ctx.done = true ctx.done = true
ctx.conn.send_string('HTTP/1.1 302 Found\r\nLocation: ${url}${ctx.headers}\r\n${headers_close}') or { return } ctx.conn.send_string('HTTP/1.1 302 Found\r\nLocation: ${url}${ctx.headers}\r\n${headers_close}') or { return Result{} }
return Result{}
} }
pub fn (mut ctx Context) not_found() Result { pub fn (mut ctx Context) not_found() Result {