-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
65 lines (58 loc) · 1.36 KB
/
handler.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
// Package handler define custom http handlers.
package handler
import (
"errors"
"io/fs"
"net/http"
"path"
)
// VueServer create a http.Handler to serve vue dist.
// You can use it like this:
//
// http.Handle("/", handler.VueServer(http.Dir("dist")))
//
// It is useful when your project have HTML5 history mode.
//
// https://router.vuejs.org/guide/essentials/history-mode.html#HTML5-Mode
func VueServer(fs http.FileSystem) http.Handler {
return &vue{
h: http.FileServer(fs),
fs: fs,
}
}
type vue struct {
h http.Handler
fs http.FileSystem
}
func (v *vue) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if f, err := v.fs.Open(path.Clean(r.URL.Path)); err == nil {
f.Close()
v.h.ServeHTTP(w, r)
return
}
f, err := v.fs.Open("index.html")
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
http.ServeContent(w, r, d.Name(), d.ModTime(), f)
}
// copy from http.toHTTPError
func toHTTPError(err error) (msg string, httpStatus int) {
if errors.Is(err, fs.ErrNotExist) {
return "404 page not found", http.StatusNotFound
}
if errors.Is(err, fs.ErrPermission) {
return "403 Forbidden", http.StatusForbidden
}
// Default:
return "500 Internal Server Error", http.StatusInternalServerError
}