-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstatic.go
68 lines (57 loc) · 1.51 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
package static
import (
"net/http"
"strings"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/labstack/echo"
)
const version = "0.0.1"
// ServeFileSystem
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
}
type binaryFileSystem struct {
fs http.FileSystem
}
func (b *binaryFileSystem) Open(name string) (http.File, error) {
return b.fs.Open(name)
}
func (b *binaryFileSystem) Exists(prefix string, filepath string) bool {
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
if _, err := b.Open(p); err != nil {
return false
}
return true
}
return false
}
func BinaryFileSystem(fs *assetfs.AssetFS) *binaryFileSystem {
return &binaryFileSystem{fs}
}
func ServeRoot(urlPrefix string, fs *assetfs.AssetFS) echo.MiddlewareFunc {
return Serve(urlPrefix, BinaryFileSystem(fs))
}
// Serve Static returns a middleware handler that serves static files in the given directory.
func Serve(urlPrefix string, fs ServeFileSystem) echo.MiddlewareFunc {
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(before echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := before(c)
if err != nil {
if c, ok := err.(*echo.HTTPError); !ok || c.Code != http.StatusNotFound {
return err
}
}
w, r := c.Response(), c.Request()
if fs.Exists(urlPrefix, r.URL.Path) {
fileserver.ServeHTTP(w, r)
return nil
}
return err
}
}
}