-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
60 lines (50 loc) · 1.25 KB
/
main.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
// adapted from https://gist.github.com/lummie/91cd1c18b2e32fa9f316862221a6fd5c
package main
import (
"log"
"net/http"
"os"
"path"
"strings"
)
type FSHandler404 = func(w http.ResponseWriter, r *http.Request) (doDefaultFileServe bool)
func fileSystem404(w http.ResponseWriter, r *http.Request) (doDefaultFileServe bool) {
//if not found redirect to /
r.URL.Path = "/"
return true
}
func FileServerWith404(root http.FileSystem, handler404 FSHandler404) http.Handler {
fs := http.FileServer(root)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//make sure the url path starts with /
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
upath = path.Clean(upath)
// attempt to open the file via the http.FileSystem
f, err := root.Open(upath)
if err != nil {
if os.IsNotExist(err) {
// call handler
if handler404 != nil {
doDefault := handler404(w, r)
if !doDefault {
return
}
}
}
}
// close if successfully opened
if err == nil {
f.Close()
}
// default serve
fs.ServeHTTP(w, r)
})
}
func main() {
http.Handle("/", FileServerWith404(http.Dir(os.Args[1]), fileSystem404))
log.Fatal(http.ListenAndServe(":80", nil))
}