vfmt: fix eating of `app.$method(vars)`; format vlib/vweb/vweb.v

pull/6836/head
Delyan Angelov 2020-11-14 13:55:10 +02:00
parent ba8cdb2977
commit 2dc9a45e06
3 changed files with 247 additions and 154 deletions

View File

@ -821,6 +821,8 @@ pub fn (mut f Fmt) expr(node ast.Expr) {
ast.ComptimeCall { ast.ComptimeCall {
if node.is_vweb { if node.is_vweb {
f.write('$' + 'vweb.html()') f.write('$' + 'vweb.html()')
} else {
f.write('${node.left}.\$${node.method_name}($node.args_var)')
} }
} }
ast.ConcatExpr { ast.ConcatExpr {

View File

@ -0,0 +1,89 @@
struct App {
a string
b string
mut:
c int
d f32
pub:
e f32
f u64
pub mut:
g string
h byte
}
fn comptime_for() {
println(@FN)
$for method in App.methods {
println(' method: $method.name | $method')
}
}
fn comptime_for_with_if() {
println(@FN)
$for method in App.methods {
println(' method: $method')
$if method.typ is fn () {
assert method.name in ['run', 'method2']
}
$if method.return_type is int {
assert method.name in ['int_method1', 'int_method2']
}
$if method.args[0].typ is string {
assert method.name == 'my_method'
}
}
}
fn comptime_for_fields() {
println(@FN)
$for field in App.fields {
println(' field: $field.name | $field')
$if field.typ is string {
assert field.name in ['a', 'b', 'g']
}
$if field.typ is f32 {
assert field.name in ['d', 'e']
}
if field.is_mut {
assert field.name in ['c', 'd', 'g', 'h']
}
if field.is_pub {
assert field.name in ['e', 'f', 'g', 'h']
}
if field.is_pub && field.is_mut {
assert field.name in ['g', 'h']
}
}
}
struct Result {
}
fn (mut a App) my_method(p string) Result {
println('>>>> ${@FN} | p: $p')
return Result{}
}
fn handle_conn<T>(mut app T) {
mut vars := []string{cap: 123}
vars << 'abc'
vars << 'def'
$for method in T.methods {
$if method.return_type is Result {
app.$method(vars)
}
}
}
fn comptime_call_dollar_method() {
mut app := App{}
handle_conn<App>(mut app)
}
fn main() {
comptime_for()
comptime_for_with_if()
comptime_for_fields()
comptime_call_dollar_method()
}

View File

@ -1,7 +1,6 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved. // Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license // Use of this source code is governed by an MIT license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module vweb module vweb
import os import os
@ -12,70 +11,74 @@ import strings
import time import time
pub const ( pub const (
methods_with_form = [http.Method.post, .put, .patch] methods_with_form = [http.Method.post, .put, .patch]
header_server = 'Server: VWeb\r\n' header_server = 'Server: VWeb\r\n'
header_connection_close = 'Connection: close\r\n' header_connection_close = 'Connection: close\r\n'
headers_close = '${header_server}${header_connection_close}\r\n' headers_close = '$header_server$header_connection_close\r\n'
http_404 = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n${headers_close}404 Not Found' http_404 = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n${headers_close}404 Not Found'
http_500 = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n${headers_close}500 Internal Server Error' http_500 = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n${headers_close}500 Internal Server Error'
mime_types = { mime_types = {
'.css': 'text/css; charset=utf-8', '.css': 'text/css; charset=utf-8'
'.gif': 'image/gif', '.gif': 'image/gif'
'.htm': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8'
'.html': 'text/html; charset=utf-8', '.html': 'text/html; charset=utf-8'
'.jpg': 'image/jpeg', '.jpg': 'image/jpeg'
'.js': 'application/javascript', '.js': 'application/javascript'
'.json': 'application/json', '.json': 'application/json'
'.md': 'text/markdown; charset=utf-8', '.md': 'text/markdown; charset=utf-8'
'.pdf': 'application/pdf', '.pdf': 'application/pdf'
'.png': 'image/png', '.png': 'image/png'
'.svg': 'image/svg+xml', '.svg': 'image/svg+xml'
'.txt': 'text/plain; charset=utf-8', '.txt': 'text/plain; charset=utf-8'
'.wasm': 'application/wasm', '.wasm': 'application/wasm'
'.xml': 'text/xml; charset=utf-8' '.xml': 'text/xml; charset=utf-8'
} }
max_http_post_size = 1024 * 1024 max_http_post_size = 1024 * 1024
default_port = 8080 default_port = 8080
) )
pub struct Context { pub struct Context {
mut: mut:
static_files map[string]string static_files map[string]string
static_mime_types map[string]string static_mime_types map[string]string
content_type string = 'text/plain' content_type string = 'text/plain'
status string = '200 OK' status string = '200 OK'
pub: pub:
req http.Request req http.Request
conn net.Socket conn net.Socket
// TODO Response // TODO Response
pub mut: pub mut:
form map[string]string form map[string]string
query map[string]string query map[string]string
headers string // response headers headers string // response headers
done bool done bool
page_gen_start i64 page_gen_start i64
form_error string form_error string
} }
pub struct Cookie { pub struct Cookie {
name string name string
value string value string
expires time.Time expires time.Time
secure bool secure bool
http_only bool http_only bool
} }
pub struct Result {} pub struct Result {
}
fn (mut ctx Context) send_response_to_client(mimetype string, res string) bool { fn (mut ctx Context) send_response_to_client(mimetype string, res string) bool {
if ctx.done { return false } if ctx.done {
return false
}
ctx.done = true ctx.done = true
mut sb := strings.new_builder(1024) mut sb := strings.new_builder(1024)
defer { sb.free() } defer {
sb.write('HTTP/1.1 ${ctx.status}') sb.free()
sb.write('\r\nContent-Type: ${mimetype}') }
sb.write('\r\nContent-Length: ${res.len}') sb.write('HTTP/1.1 $ctx.status')
sb.write('\r\nContent-Type: $mimetype')
sb.write('\r\nContent-Length: $res.len')
sb.write(ctx.headers) sb.write(ctx.headers)
sb.write('\r\n') sb.write('\r\n')
sb.write(headers_close) sb.write(headers_close)
@ -84,7 +87,9 @@ fn (mut ctx Context) send_response_to_client(mimetype string, res string) bool {
defer { defer {
s.free() s.free()
} }
ctx.conn.send_string(s) or { return false } ctx.conn.send_string(s) or {
return false
}
return true return true
} }
@ -108,26 +113,32 @@ pub fn (mut ctx Context) ok(s string) Result {
} }
pub fn (mut ctx Context) redirect(url string) Result { pub fn (mut ctx Context) redirect(url string) Result {
if ctx.done { return Result{} } 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 Result{} } ctx.conn.send_string('HTTP/1.1 302 Found\r\nLocation: $url$ctx.headers\r\n$headers_close') or {
return Result{}
}
return Result{} return Result{}
} }
pub fn (mut ctx Context) not_found() Result { pub fn (mut ctx Context) not_found() Result {
if ctx.done { return vweb.Result{} } if ctx.done {
return Result{}
}
ctx.done = true ctx.done = true
ctx.conn.send_string(http_404) or {} ctx.conn.send_string(http_404) or { }
return vweb.Result{} return Result{}
} }
pub fn (mut ctx Context) set_cookie(cookie Cookie) { pub fn (mut ctx Context) set_cookie(cookie Cookie) {
mut cookie_data := []string{} mut cookie_data := []string{}
mut secure := if cookie.secure { "Secure;" } else { "" } mut secure := if cookie.secure { 'Secure;' } else { '' }
secure += if cookie.http_only { " HttpOnly" } else { " " } secure += if cookie.http_only { ' HttpOnly' } else { ' ' }
cookie_data << secure cookie_data << secure
if cookie.expires.unix > 0 { if cookie.expires.unix > 0 {
cookie_data << 'expires=${cookie.expires.utc_string()}' cookie_data << 'expires=$cookie.expires.utc_string()'
} }
data := cookie_data.join(' ') data := cookie_data.join(' ')
ctx.add_header('Set-Cookie', '$cookie.name=$cookie.value; $data') ctx.add_header('Set-Cookie', '$cookie.name=$cookie.value; $data')
@ -135,8 +146,8 @@ pub fn (mut ctx Context) set_cookie(cookie Cookie) {
pub fn (mut ctx Context) set_cookie_old(key string, val string) { pub fn (mut ctx Context) set_cookie_old(key string, val string) {
// TODO support directives, escape cookie value (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) // TODO support directives, escape cookie value (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)
//ctx.add_header('Set-Cookie', '${key}=${val}; Secure; HttpOnly') // ctx.add_header('Set-Cookie', '${key}=${val}; Secure; HttpOnly')
ctx.add_header('Set-Cookie', '${key}=${val}; HttpOnly') ctx.add_header('Set-Cookie', '$key=$val; HttpOnly')
} }
pub fn (mut ctx Context) set_content_type(typ string) { pub fn (mut ctx Context) set_content_type(typ string) {
@ -144,7 +155,7 @@ pub fn (mut ctx Context) set_content_type(typ string) {
} }
pub fn (mut ctx Context) set_cookie_with_expire_date(key string, val string, expire_date time.Time) { pub fn (mut ctx Context) set_cookie_with_expire_date(key string, val string, expire_date time.Time) {
ctx.add_header('Set-Cookie', '$key=$val; Secure; HttpOnly; expires=${expire_date.utc_string()}') ctx.add_header('Set-Cookie', '$key=$val; Secure; HttpOnly; expires=$expire_date.utc_string()')
} }
pub fn (ctx &Context) get_cookie(key string) ?string { // TODO refactor pub fn (ctx &Context) get_cookie(key string) ?string { // TODO refactor
@ -153,13 +164,10 @@ pub fn (ctx &Context) get_cookie(key string) ?string { // TODO refactor
cookie_header = ctx.get_header('Cookie') cookie_header = ctx.get_header('Cookie')
} }
cookie_header = ' ' + cookie_header cookie_header = ' ' + cookie_header
//println('cookie_header="$cookie_header"') // println('cookie_header="$cookie_header"')
//println(ctx.req.headers) // println(ctx.req.headers)
cookie := if cookie_header.contains(';') { cookie := if cookie_header.contains(';') { cookie_header.find_between(' $key=', ';') } else { cookie_header.find_between(' $key=',
cookie_header.find_between(' $key=', ';') '\r') }
} else {
cookie_header.find_between(' $key=', '\r')
}
if cookie != '' { if cookie != '' {
return cookie.trim_space() return cookie.trim_space()
} }
@ -175,20 +183,18 @@ pub fn (mut ctx Context) set_status(code int, desc string) {
} }
pub fn (mut ctx Context) add_header(key string, val string) { pub fn (mut ctx Context) add_header(key string, val string) {
//println('add_header($key, $val)') // println('add_header($key, $val)')
ctx.headers = ctx.headers + '\r\n$key: $val' ctx.headers = ctx.headers + '\r\n$key: $val'
//println(ctx.headers) // println(ctx.headers)
} }
pub fn (ctx &Context) get_header(key string) string { pub fn (ctx &Context) get_header(key string) string {
return ctx.req.headers[key] return ctx.req.headers[key]
} }
//fn handle_conn(conn net.Socket) { // fn handle_conn(conn net.Socket) {
//println('handle') // println('handle')
// }
//}
pub fn run<T>(port int) { pub fn run<T>(port int) {
mut app := T{} mut app := T{}
run_app<T>(mut app, port) run_app<T>(mut app, port)
@ -196,7 +202,9 @@ pub fn run<T>(port int) {
pub fn run_app<T>(mut app T, port int) { pub fn run_app<T>(mut app T, port int) {
println('Running a Vweb app on http://localhost:$port') println('Running a Vweb app on http://localhost:$port')
l := net.listen(port) or { panic('failed to listen') } l := net.listen(port) or {
panic('failed to listen')
}
app.vweb = Context{} app.vweb = Context{}
app.init_once() app.init_once()
$for method in T.methods { $for method in T.methods {
@ -204,16 +212,18 @@ pub fn run_app<T>(mut app T, port int) {
// check routes for validity // check routes for validity
} }
} }
//app.reset() // app.reset()
for { for {
conn := l.accept() or { panic('accept() failed') } conn := l.accept() or {
//handle_conn<T>(conn, mut app) panic('accept() failed')
}
// handle_conn<T>(conn, mut app)
handle_conn<T>(conn, mut app) handle_conn<T>(conn, mut app)
//app.vweb.page_gen_time = time.ticks() - t // app.vweb.page_gen_time = time.ticks() - t
//eprintln('handle conn() took ${time.ticks()-t}ms') // eprintln('handle conn() took ${time.ticks()-t}ms')
//message := readall(conn) // message := readall(conn)
//println(message) // println(message)
/* /*
if message.len > max_http_post_size { if message.len > max_http_post_size {
println('message.len = $message.len > max_http_post_size') println('message.len = $message.len > max_http_post_size')
conn.send_string(http_500) or {} conn.send_string(http_500) or {}
@ -221,11 +231,9 @@ pub fn run_app<T>(mut app T, port int) {
continue continue
} }
*/ */
// lines := message.split_into_lines()
//lines := message.split_into_lines() // println(lines)
//println(lines) /*
/*
if lines.len < 2 { if lines.len < 2 {
conn.send_string(http_500) or {} conn.send_string(http_500) or {}
conn.close() or {} conn.close() or {}
@ -236,65 +244,64 @@ pub fn run_app<T>(mut app T, port int) {
} }
fn handle_conn<T>(conn net.Socket, mut app T) { fn handle_conn<T>(conn net.Socket, mut app T) {
defer { conn.close() or {} } defer {
//fn handle_conn<T>(conn net.Socket, app_ T) T { conn.close() or { }
//mut app := app_ }
//first_line := strip(lines[0]) // fn handle_conn<T>(conn net.Socket, app_ T) T {
// mut app := app_
// first_line := strip(lines[0])
page_gen_start := time.ticks() page_gen_start := time.ticks()
first_line := conn.read_line() first_line := conn.read_line()
$if debug { $if debug {
println('firstline="$first_line"') println('firstline="$first_line"')
} }
// Parse the first line // Parse the first line
// "GET / HTTP/1.1" // "GET / HTTP/1.1"
//first_line := s.all_before('\n') // first_line := s.all_before('\n')
vals := first_line.split(' ') vals := first_line.split(' ')
if vals.len < 2 { if vals.len < 2 {
println('no vals for http') println('no vals for http')
conn.send_string(http_500) or {} conn.send_string(http_500) or { }
return return
//continue
} }
mut headers := []string{} mut headers := []string{}
mut body := '' mut body := ''
mut in_headers := true mut in_headers := true
mut len := 0 mut len := 0
//for line in lines[1..] { // for line in lines[1..] {
for _ in 0..100 { for _ in 0 .. 100 {
//println(j) // println(j)
line := conn.read_line() line := conn.read_line()
sline := strip(line) sline := strip(line)
if sline == '' { if sline == '' {
//if in_headers { // if in_headers {
// End of headers, no body => exit // End of headers, no body => exit
if len == 0 { if len == 0 {
break break
} }
//} //else { // } //else {
// End of body // End of body
//break // break
//} // }
in_headers = false in_headers = false
} }
if in_headers { if in_headers {
//println(sline) // println(sline)
headers << sline headers << sline
if sline.starts_with('Content-Length') { if sline.starts_with('Content-Length') {
len = sline.all_after(': ').int() len = sline.all_after(': ').int()
//println('GOT CL=$len') // println('GOT CL=$len')
} }
} else { } else {
body += line.trim_left('\r\n') body += line.trim_left('\r\n')
if body.len >= len { if body.len >= len {
break break
} }
//println('body:$body') // println('body:$body')
} }
} }
req := http.Request{ req := http.Request{
headers: http.parse_headers(headers) //s.split_into_lines()) headers: http.parse_headers(headers) // s.split_into_lines())
data: strip(body) data: strip(body)
ws_func: 0 ws_func: 0
user_ptr: 0 user_ptr: 0
@ -304,19 +311,19 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
$if debug { $if debug {
println('req.headers = ') println('req.headers = ')
println(req.headers) println(req.headers)
println('req.data="$req.data"' ) println('req.data="$req.data"')
//println('vweb action = "$action"') // println('vweb action = "$action"')
} }
//mut app := T{ // mut app := T{
app.vweb = Context{ app.vweb = Context{
req: req req: req
conn: conn conn: conn
form: map[string]string form: map[string]string{}
static_files: app.vweb.static_files static_files: app.vweb.static_files
static_mime_types: app.vweb.static_mime_types static_mime_types: app.vweb.static_mime_types
page_gen_start: page_gen_start page_gen_start: page_gen_start
} }
//} // }
if req.method in methods_with_form { if req.method in methods_with_form {
app.vweb.parse_form(req.data) app.vweb.parse_form(req.data)
} }
@ -325,9 +332,7 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
println('no vals for http') println('no vals for http')
} }
return return
//continue
} }
// Serve a static file if it is one // Serve a static file if it is one
// TODO: handle url parameters properly - for now, ignore them // TODO: handle url parameters properly - for now, ignore them
mut static_file_name := app.vweb.req.url mut static_file_name := app.vweb.req.url
@ -336,10 +341,9 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
} }
static_file := app.vweb.static_files[static_file_name] static_file := app.vweb.static_files[static_file_name]
mime_type := app.vweb.static_mime_types[static_file_name] mime_type := app.vweb.static_mime_types[static_file_name]
if static_file != '' && mime_type != '' { if static_file != '' && mime_type != '' {
data := os.read_file(static_file) or { data := os.read_file(static_file) or {
conn.send_string(http_404) or {} conn.send_string(http_404) or { }
return return
} }
app.vweb.send_response_to_client(mime_type, data) app.vweb.send_response_to_client(mime_type, data)
@ -347,19 +351,16 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
return return
} }
app.init() app.init()
// Call the right action // Call the right action
$if debug { $if debug {
println('route matching...') println('route matching...')
} }
//t := time.ticks() // t := time.ticks()
//mut action := '' // mut action := ''
mut route_words_a := [][]string{} mut route_words_a := [][]string{}
//mut url_words := vals[1][1..].split('/').filter(it != '') // mut url_words := vals[1][1..].split('/').filter(it != '')
x := vals[1][1..].split('/') x := vals[1][1..].split('/')
mut url_words := x.filter(it != '') mut url_words := x.filter(it != '')
if url_words.len == 0 { if url_words.len == 0 {
app.index() app.index()
return return
@ -376,7 +377,6 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
} }
} }
} }
mut vars := []string{cap: route_words_a.len} mut vars := []string{cap: route_words_a.len}
mut action := '' mut action := ''
$for method in T.methods { $for method in T.methods {
@ -388,7 +388,9 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
// since such methods have a priority. // since such methods have a priority.
// For example URL `/register` matches route `/:user`, but `fn register()` // For example URL `/register` matches route `/:user`, but `fn register()`
// should be called first. // should be called first.
if (req.method == .get && url_words[0] == method.name && url_words.len == 1) || (req.method == .post && url_words[0] + '_post' == method.name) { if (req.method == .get &&
url_words[0] == method.name && url_words.len == 1) ||
(req.method == .post && url_words[0] + '_post' == method.name) {
$if debug { $if debug {
println('easy match method=$method.name') println('easy match method=$method.name')
} }
@ -427,12 +429,13 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
} }
if route_words_a.len > 0 { if route_words_a.len > 0 {
for route_words in route_words_a { for route_words in route_words_a {
if url_words.len == route_words.len || (url_words.len >= route_words.len - 1 && route_words.last().ends_with('...')) { if url_words.len == route_words.len ||
(url_words.len >= route_words.len - 1 && route_words.last().ends_with('...')) {
// match `/:user/:repo/tree` to `/vlang/v/tree` // match `/:user/:repo/tree` to `/vlang/v/tree`
mut matching := false mut matching := false
mut unknown := false mut unknown := false
mut variables := []string{cap: route_words.len} mut variables := []string{cap: route_words.len}
for i in 0..route_words.len { for i in 0 .. route_words.len {
if url_words.len == i { if url_words.len == i {
variables << '' variables << ''
matching = true matching = true
@ -477,7 +480,7 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
} }
if action == '' { if action == '' {
// site not found // site not found
conn.send_string(http_404) or {} conn.send_string(http_404) or { }
return return
} }
$for method in T.methods { $for method in T.methods {
@ -488,7 +491,7 @@ fn handle_conn<T>(conn net.Socket, mut app T) {
if method.args.len == vars.len { if method.args.len == vars.len {
app.$method(vars) app.$method(vars)
} else { } else {
eprintln('warning: uneven parameters count (${method.args.len}) in `$method.name`, compared to the vweb route `$method.attrs` (${vars.len})') eprintln('warning: uneven parameters count ($method.args.len) in `$method.name`, compared to the vweb route `$method.attrs` ($vars.len)')
} }
} }
} }
@ -499,9 +502,9 @@ fn (mut ctx Context) parse_form(s string) {
if ctx.req.method !in methods_with_form { if ctx.req.method !in methods_with_form {
return return
} }
//pos := s.index('\r\n\r\n') // pos := s.index('\r\n\r\n')
//if pos > -1 { // if pos > -1 {
mut str_form := s//[pos..s.len] mut str_form := s // [pos..s.len]
str_form = str_form.replace('+', ' ') str_form = str_form.replace('+', ' ')
words := str_form.split('&') words := str_form.split('&')
for word in words { for word in words {
@ -509,7 +512,9 @@ fn (mut ctx Context) parse_form(s string) {
println('parse form keyval="$word"') println('parse form keyval="$word"')
} }
keyval := word.trim_space().split('=') keyval := word.trim_space().split('=')
if keyval.len != 2 { continue } if keyval.len != 2 {
continue
}
key := urllib.query_unescape(keyval[0]) or { key := urllib.query_unescape(keyval[0]) or {
continue continue
} }
@ -521,26 +526,26 @@ fn (mut ctx Context) parse_form(s string) {
} }
ctx.form[key] = val ctx.form[key] = val
} }
//} // }
// todo: parse form-data and application/json // todo: parse form-data and application/json
// ... // ...
} }
fn (mut ctx Context) scan_static_directory(directory_path string, mount_path string) { fn (mut ctx Context) scan_static_directory(directory_path string, mount_path string) {
files := os.ls(directory_path) or { panic(err) } files := os.ls(directory_path) or {
panic(err)
}
if files.len > 0 { if files.len > 0 {
for file in files { for file in files {
if os.is_dir(file) { if os.is_dir(file) {
ctx.scan_static_directory(directory_path + '/' + file, mount_path + '/' + file) ctx.scan_static_directory(directory_path + '/' + file, mount_path + '/' + file)
} else if file.contains('.') && ! file.starts_with('.') && ! file.ends_with('.') { } else if file.contains('.') && !file.starts_with('.') && !file.ends_with('.') {
ext := os.file_ext(file) ext := os.file_ext(file)
// Rudimentary guard against adding files not in mime_types. // Rudimentary guard against adding files not in mime_types.
// Use serve_static directly to add non-standard mime types. // Use serve_static directly to add non-standard mime types.
if ext in mime_types { if ext in mime_types {
ctx.serve_static(mount_path + '/' + file, directory_path + '/' + file, mime_types[ext]) ctx.serve_static(mount_path + '/' + file, directory_path + '/' + file,
mime_types[ext])
} }
} }
} }
@ -548,24 +553,19 @@ fn (mut ctx Context) scan_static_directory(directory_path string, mount_path str
} }
pub fn (mut ctx Context) handle_static(directory_path string) bool { pub fn (mut ctx Context) handle_static(directory_path string) bool {
if ctx.done || ! os.exists(directory_path) { if ctx.done || !os.exists(directory_path) {
return false return false
} }
dir_path := directory_path.trim_space().trim_right('/') dir_path := directory_path.trim_space().trim_right('/')
mut mount_path := '' mut mount_path := ''
if dir_path != '.' && os.is_dir(dir_path) { if dir_path != '.' && os.is_dir(dir_path) {
// Mount point hygene, "./assets" => "/assets". // Mount point hygene, "./assets" => "/assets".
mount_path = '/' + dir_path.trim_left('.').trim('/') mount_path = '/' + dir_path.trim_left('.').trim('/')
} }
ctx.scan_static_directory(dir_path, mount_path) ctx.scan_static_directory(dir_path, mount_path)
return true return true
} }
pub fn (mut ctx Context) serve_static(url string, file_path string, mime_type string) { pub fn (mut ctx Context) serve_static(url string, file_path string, mime_type string) {
ctx.static_files[url] = file_path ctx.static_files[url] = file_path
ctx.static_mime_types[url] = mime_type ctx.static_mime_types[url] = mime_type
@ -580,7 +580,9 @@ pub fn (ctx &Context) ip() string {
ip = ip.all_before(',') ip = ip.all_before(',')
} }
if ip == '' { if ip == '' {
ip = ctx.conn.peer_ip() or { '' } ip = ctx.conn.peer_ip() or {
''
}
} }
return ip return ip
} }
@ -589,7 +591,6 @@ pub fn (mut ctx Context) error(s string) {
ctx.form_error = s ctx.form_error = s
} }
/* /*
fn readall(conn net.Socket) string { fn readall(conn net.Socket) string {
// read all message from socket // read all message from socket
@ -606,7 +607,6 @@ fn readall(conn net.Socket) string {
return message return message
} }
*/ */
fn strip(s string) string { fn strip(s string) string {
// strip('\nabc\r\n') => 'abc' // strip('\nabc\r\n') => 'abc'
return s.trim('\r\n') return s.trim('\r\n')
@ -618,11 +618,13 @@ pub fn not_found() Result {
fn filter(s string) string { fn filter(s string) string {
return s.replace_each([ return s.replace_each([
'<', '&lt;', '<',
'"', '&quot;', '&lt;',
'&', '&amp;', '"',
'&quot;',
'&',
'&amp;',
]) ])
} }
pub type RawHtml = string pub type RawHtml = string