diff --git a/vlib/vweb/tests/test_app.v b/vlib/vweb/tests/test_app.v new file mode 100644 index 0000000000..213fdb9114 --- /dev/null +++ b/vlib/vweb/tests/test_app.v @@ -0,0 +1,30 @@ +module main + +import vweb + +const ( + Port = 8082 +) + +struct App { +pub mut: + vweb vweb.Context // TODO embed +} + +fn main() { + println('Running vweb test on http://localhost:$Port') + vweb.run(Port) +} + +pub fn (app mut App) init() { + app.vweb.serve_static('/css.css', 'static/css.css') + app.vweb.serve_static('/jquery.js', 'static/jquery.js') +} + +pub fn (app mut App) json_endpoint() { + app.vweb.json('{"a": 3}') +} + +pub fn (app mut App) index() { + app.vweb.text('hello world') +} diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 2824aedd91..2cdb1c78a1 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -12,8 +12,18 @@ pub: req http.Request conn net.Socket post_form map[string]string + static_files map[string]string // TODO Response - headers []string + headers []string // response headers +} + +pub fn (ctx Context) text(s string) { + h := ctx.headers.join('\n') + ctx.conn.write('HTTP/1.1 200 OK +Content-Type: text/plain +$h +$s +') } pub fn (ctx Context) json(s string) { @@ -88,8 +98,10 @@ pub fn run(port int) { req: req conn: conn post_form: map[string]string{} + static_files: map[string]string{} } } +println('calling init') app.init() if req.method == 'POST' { app.vweb.parse_form(s) @@ -99,6 +111,12 @@ pub fn run(port int) { println('no vals for http') return } + // Serve a static file if it's one + if app.vweb.handle_static() { + conn.close() + continue + } + // Call the right action app.$action() conn.close() } @@ -124,4 +142,22 @@ fn (ctx mut Context) parse_form(s string) { } } +fn (ctx mut Context) handle_static() bool { + static_file := ctx.static_files[ctx.req.url] + if static_file != '' { + data := os.read_file(static_file) or { return false } + ctx.conn.write('HTTP/1.1 200 OK +Content-Type: text/css + +$data +') + return true + } + return false +} + +pub fn (ctx mut Context) serve_static(url, file_path string) { + ctx.static_files[url] = file_path +} +