/
static.jl
65 lines (57 loc) 路 2.23 KB
/
static.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# module Bukdu.Plug
struct Static <: AbstractPlug
end
struct StaticController <: ApplicationController
conn::Conn
end
function content_type_for_file_extionsion(ext)::String
mimes = Dict(
".html" => "text/html; charset=utf-8",
".htm" => "text/html; charset=utf-8",
".js" => "text/javascript",
".wasm" => "application/wasm",
".css" => "text/css",
)
get(mimes, ext, "application/octet-stream")
end
"""
plug(::Type{Static}; at::String, from::String, only::Union{Vector{String},Nothing}=nothing, indexfile="index.html")
"""
function plug(::Type{Static}; at::String, from::String, only::Union{Vector{String},Nothing}=nothing, indexfile="index.html")
function _readfile_base(c::StaticController, f)
reqpath = c.conn.request.target
offset = isdirpath(at) ? 1 : 2
targetpath = reqpath[length(at)+offset:end]
filepath = joinpath(f(from, targetpath)...)
(_, fileext) = splitext(filepath)
ext = lowercase(fileext)
Render(content_type_for_file_extionsion(ext), read, filepath)
end # function _readfile_base
function readfile(c::StaticController)
_readfile_base(c, (from, targetpath) -> (from, targetpath))
end # function readfile
function readindexfile(c::StaticController)
_readfile_base(c, (from, targetpath) -> (from, targetpath, indexfile))
end # function readindexfile
has_only = only isa Vector{String} && !isempty(only)
for (root, dirs, files) in walkdir(from)
subpath = root[length(from)+1:end]
for filename in files
if has_only
subfilepath = normpath(subpath, filename)
!any(x->startswith(subfilepath, x), only) && continue # for filename
end
if filename == indexfile
reqindex = normpath(at, subpath)
get(reqindex, StaticController, readindexfile)
end
reqpath = normpath(at, subpath, filename)
if Sys.iswindows()
path_arr = split(reqpath, Base.Filesystem.path_separator)
reqpath = join(path_arr, '/')
end
get(reqpath, StaticController, readfile)
end
end
end
# module Bukdu.Plug