From cd423251da69985f3835d4afd516dca3511f311a Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Tue, 2 Mar 2021 21:30:18 +0200 Subject: [PATCH] vweb: add .mount_static_folder_at/2 , use it instead of app.handle_static in the server_sent_events example --- examples/vweb/server_sent_events/server.v | 3 ++- vlib/vweb/vweb.v | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/examples/vweb/server_sent_events/server.v b/examples/vweb/server_sent_events/server.v index 3fe1be1e8c..b4e66f935c 100644 --- a/examples/vweb/server_sent_events/server.v +++ b/examples/vweb/server_sent_events/server.v @@ -1,5 +1,6 @@ module main +import os import rand import time import vweb @@ -15,7 +16,7 @@ fn main() { pub fn (mut app App) init_once() { app.serve_static('/favicon.ico', 'favicon.ico', 'img/x-icon') - app.handle_static('.', false) + app.mount_static_folder_at(os.resource_abs_path('.'), '/') } pub fn (mut app App) index() vweb.Result { diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 734b85ff10..a3557b10a6 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -575,7 +575,7 @@ fn (mut ctx Context) scan_static_directory(directory_path string, mount_path str files := os.ls(directory_path) or { panic(err) } if files.len > 0 { for file in files { - full_path := directory_path + '/' + file + full_path := os.join_path(directory_path, file) if os.is_dir(full_path) { ctx.scan_static_directory(full_path, mount_path + '/' + file) } else if file.contains('.') && !file.starts_with('.') && !file.ends_with('.') { @@ -606,6 +606,19 @@ pub fn (mut ctx Context) handle_static(directory_path string, root bool) bool { return true } +// mount_static_folder_at - makes all static files in `directory_path` and inside it, available at http://server/mount_path +// For example: suppose you have called .mount_static_folder_at('/var/share/myassets', '/assets'), +// and you have a file /var/share/myassets/main.css . +// => That file will be available at URL: http://server/assets/main.css . +pub fn (mut ctx Context) mount_static_folder_at(directory_path string, mount_path string) bool { + if ctx.done || mount_path.len < 1 || mount_path[0] != `/` || !os.exists(directory_path) { + return false + } + dir_path := directory_path.trim_right('/') + ctx.scan_static_directory(dir_path, mount_path[1..]) + return true +} + // Serves a file static // `url` is the access path on the site, `file_path` is the real path to the file, `mime_type` is the file type pub fn (mut ctx Context) serve_static(url string, file_path string, mime_type string) {