-
Notifications
You must be signed in to change notification settings - Fork 28
/
spa_webapp.go
61 lines (53 loc) · 1.61 KB
/
spa_webapp.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
//go:build webapp
// +build webapp
package main
import (
"embed"
"io/fs"
"net/http"
"os"
"path/filepath"
)
//go:embed ui/build/*
var staticFiles embed.FS
type spaHandler struct {
staticFS embed.FS
staticPath string
indexPath string
}
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
_, err = h.staticFS.Open(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
index, err := h.staticFS.ReadFile(filepath.Join(h.staticPath, h.indexPath))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusAccepted)
w.Write(index)
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// get the subdirectory of the static dir
statics, err := fs.Sub(h.staticFS, h.staticPath)
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.FS(statics)).ServeHTTP(w, r)
}
func getSpaHandler() http.Handler {
return spaHandler{staticFS: staticFiles, staticPath: "ui/build", indexPath: "index.html"}
}