-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
default_fs.go
39 lines (34 loc) 路 887 Bytes
/
default_fs.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
package server
import (
"net/http"
"os"
"strings"
)
type defaultRouteFS struct {
defaultFile string
fs http.FileSystem
staticPrefixes []string
}
// newDefaultRouteFS wraps an http.FileSystem and if a file isn't found, routes it to the defaultFile instead of failing
func newDefaultRouteFS(defaultFile string, fs http.FileSystem, staticPrefixes ...string) http.FileSystem {
return &defaultRouteFS{
defaultFile: defaultFile,
fs: fs,
staticPrefixes: staticPrefixes,
}
}
func (d *defaultRouteFS) Open(name string) (http.File, error) {
f, err := d.fs.Open(name)
if err == os.ErrNotExist && d.isNotPrefixed(name) {
return d.fs.Open(d.defaultFile)
}
return f, err
}
func (d *defaultRouteFS) isNotPrefixed(name string) bool {
for _, dir := range d.staticPrefixes {
if strings.HasPrefix(name, dir) {
return false
}
}
return true
}