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

vweb: add .mount_static_folder_at/2 , use it instead of app.handle_static in the server_sent_events example

This commit is contained in:
Delyan Angelov 2021-03-02 21:30:18 +02:00
parent eb4c60877e
commit cd423251da
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 16 additions and 2 deletions

View File

@ -1,5 +1,6 @@
module main module main
import os
import rand import rand
import time import time
import vweb import vweb
@ -15,7 +16,7 @@ fn main() {
pub fn (mut app App) init_once() { pub fn (mut app App) init_once() {
app.serve_static('/favicon.ico', 'favicon.ico', 'img/x-icon') 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 { pub fn (mut app App) index() vweb.Result {

View File

@ -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) } files := os.ls(directory_path) or { panic(err) }
if files.len > 0 { if files.len > 0 {
for file in files { for file in files {
full_path := directory_path + '/' + file full_path := os.join_path(directory_path, file)
if os.is_dir(full_path) { if os.is_dir(full_path) {
ctx.scan_static_directory(full_path, mount_path + '/' + file) ctx.scan_static_directory(full_path, mount_path + '/' + file)
} else if file.contains('.') && !file.starts_with('.') && !file.ends_with('.') { } 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 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 // 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 // `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) { pub fn (mut ctx Context) serve_static(url string, file_path string, mime_type string) {