2021-05-11 13:59:02 +03:00
|
|
|
module main
|
|
|
|
|
|
|
|
import vweb
|
|
|
|
import time
|
|
|
|
import sqlite
|
|
|
|
|
|
|
|
struct App {
|
|
|
|
vweb.Context
|
|
|
|
pub mut:
|
2021-08-03 16:03:16 +03:00
|
|
|
db sqlite.DB
|
2021-05-11 13:59:02 +03:00
|
|
|
user_id string
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Article {
|
|
|
|
id int
|
|
|
|
title string
|
|
|
|
text string
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_a_vweb_application_compiles() {
|
2021-05-11 14:01:57 +03:00
|
|
|
go fn () {
|
2021-05-11 13:59:02 +03:00
|
|
|
time.sleep(2 * time.second)
|
|
|
|
exit(0)
|
|
|
|
}()
|
|
|
|
vweb.run(&App{}, 18081)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut app App) before_request() {
|
|
|
|
app.user_id = app.get_cookie('id') or { '0' }
|
|
|
|
}
|
|
|
|
|
|
|
|
['/new_article'; post]
|
|
|
|
pub fn (mut app App) new_article() vweb.Result {
|
|
|
|
title := app.form['title']
|
|
|
|
text := app.form['text']
|
|
|
|
if title == '' || text == '' {
|
|
|
|
return app.text('Empty text/title')
|
|
|
|
}
|
|
|
|
article := Article{
|
|
|
|
title: title
|
|
|
|
text: text
|
|
|
|
}
|
|
|
|
println('posting article')
|
|
|
|
println(article)
|
|
|
|
sql app.db {
|
|
|
|
insert article into Article
|
|
|
|
}
|
|
|
|
|
|
|
|
return app.redirect('/')
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut app App) time() {
|
|
|
|
app.text(time.now().format())
|
|
|
|
}
|
2021-12-07 01:31:17 +03:00
|
|
|
|
|
|
|
fn (mut app App) time_json() {
|
|
|
|
app.json({
|
|
|
|
'time': time.now().format()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut app App) time_json_pretty() {
|
|
|
|
app.json_pretty({
|
|
|
|
'time': time.now().format()
|
|
|
|
})
|
|
|
|
}
|
2022-10-05 13:23:47 +03:00
|
|
|
|
|
|
|
struct ApiSuccessResponse<T> {
|
|
|
|
success bool
|
|
|
|
result T
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut app App) json_success<T>(result T) vweb.Result {
|
|
|
|
response := ApiSuccessResponse<T>{
|
|
|
|
success: true
|
|
|
|
result: result
|
|
|
|
}
|
|
|
|
|
|
|
|
return app.json(response)
|
|
|
|
}
|
|
|
|
|
|
|
|
// should compile, this is a helper method, not exposed as a route
|
|
|
|
fn (mut app App) some_helper<T>(result T) ApiSuccessResponse<T> {
|
|
|
|
response := ApiSuccessResponse<T>{
|
|
|
|
success: true
|
|
|
|
result: result
|
|
|
|
}
|
|
|
|
return response
|
|
|
|
}
|
|
|
|
|
|
|
|
// should compile, the route method itself is not generic
|
|
|
|
fn (mut app App) ok() vweb.Result {
|
|
|
|
return app.json(app.some_helper(123))
|
|
|
|
}
|