-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
79 lines (64 loc) · 1.54 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
package static
import (
"net/http"
"strings"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
type binaryFileSystem struct {
fs http.FileSystem
}
func (b *binaryFileSystem) Open(name string) (http.File, error) {
return b.fs.Open(name)
}
type StaticConfig struct {
UrlPrefix string
AssetFS *assetfs.AssetFS
Skipper middleware.Skipper
Browse bool
}
func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc {
afs := config.AssetFS
urlPrefix := config.UrlPrefix
if config.Skipper == nil {
config.Skipper = middleware.DefaultSkipper
}
fs := &binaryFileSystem{afs}
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
w, r := c.Response(), c.Request()
filepath := r.URL.Path
if p := strings.TrimPrefix(filepath, urlPrefix); len(p) < len(filepath) {
httpFile, err := fs.Open(p)
if err == nil {
fi, _ := httpFile.Stat()
if fi.IsDir() {
if config.Browse {
fileserver.ServeHTTP(w, r)
return nil
}
return next(c)
}
fileserver.ServeHTTP(w, r)
return nil
}
}
return next(c)
}
}
}
func Static(urlPrefix string, afs *assetfs.AssetFS) echo.MiddlewareFunc {
c := StaticConfig{}
c.UrlPrefix = urlPrefix
c.AssetFS = afs
c.Skipper = middleware.DefaultSkipper
return StaticWithConfig(c)
}