-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
101 lines (72 loc) · 1.85 KB
/
static.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package www
import (
"fmt"
"github.com/aaronland/go-http-rewrite"
"github.com/sfomuseum/go-www-geotag/static"
"io/fs"
gohttp "net/http"
"path/filepath"
"strings"
)
func StaticFileSystem() (gohttp.FileSystem, error) {
http_fs := gohttp.FS(static.FS)
return http_fs, nil
}
func StaticAssetsHandler() (gohttp.Handler, error) {
http_fs, err := StaticFileSystem()
if err != nil {
return nil, err
}
return gohttp.FileServer(http_fs), nil
}
func StaticAssetsHandlerWithPrefix(prefix string) (gohttp.Handler, error) {
fs_handler, err := StaticAssetsHandler()
if err != nil {
return nil, err
}
prefix = strings.TrimRight(prefix, "/")
if prefix == "" {
return fs_handler, nil
}
rewrite_func := func(req *gohttp.Request) (*gohttp.Request, error) {
req.URL.Path = strings.Replace(req.URL.Path, prefix, "", 1)
return req, nil
}
rewrite_handler := rewrite.RewriteRequestHandler(fs_handler, rewrite_func)
return rewrite_handler, nil
}
func AppendStaticAssetHandlers(mux *gohttp.ServeMux) error {
return AppendStaticAssetHandlersWithPrefix(mux, "")
}
func AppendStaticAssetHandlersWithPrefix(mux *gohttp.ServeMux, prefix string) error {
asset_handler, err := StaticAssetsHandlerWithPrefix(prefix)
if err != nil {
return nil
}
walk_func := func(path string, info fs.DirEntry, err error) error {
if path == "." {
return nil
}
if info.IsDir() {
return nil
}
if prefix != "" {
path = appendPrefix(prefix, path)
}
if !strings.HasPrefix(path, "/") {
path = fmt.Sprintf("/%s", path)
}
// log.Println("APPEND", path)
mux.Handle(path, asset_handler)
return nil
}
return fs.WalkDir(static.FS, ".", walk_func)
}
func appendPrefix(prefix string, path string) string {
prefix = strings.TrimRight(prefix, "/")
if prefix != "" {
path = strings.TrimLeft(path, "/")
path = filepath.Join(prefix, path)
}
return path
}