-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdevserver.go
46 lines (40 loc) · 841 Bytes
/
devserver.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
package main
import (
"fmt"
"io"
"net/http"
"os"
"path"
)
func SendFile(w io.Writer, filePath string) {
f, err := os.Open(filePath)
if err != nil {
fmt.Fprintf(w, err.Error())
return
}
defer f.Close()
_, err = io.Copy(w, f)
if err != nil {
fmt.Fprintf(w, err.Error())
return
}
}
func NotFound(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintf(w, "my 404 page!")
SendFile(w, "website/404.html")
}
func FileServerWithCustom404(fs http.FileSystem) http.Handler {
fsh := http.FileServer(fs)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := fs.Open(path.Clean(r.URL.Path))
if os.IsNotExist(err) {
NotFound(w, r)
return
}
fsh.ServeHTTP(w, r)
})
}
func main() {
servedDir := "website/"
http.ListenAndServe(":8000", FileServerWithCustom404(http.Dir(servedDir)))
}