dorfylegends/backend/server/static.go

62 lines
1.5 KiB
Go
Raw Normal View History

2022-05-01 13:29:39 +03:00
package server
import (
"io/fs"
2022-05-03 15:59:47 +03:00
"io/ioutil"
2022-05-01 13:29:39 +03:00
"net/http"
"os"
2022-05-09 18:20:31 +03:00
"strings"
2022-05-01 13:29:39 +03:00
)
type spaHandler struct {
server *DfServer
2022-05-03 15:59:47 +03:00
staticFS fs.FS
2022-05-01 13:29:39 +03:00
staticPath string
indexPath string
}
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path := r.URL.Path
2022-05-09 18:20:31 +03:00
path = strings.TrimPrefix(path, h.server.context.config.SubUri)
2022-05-01 13:29:39 +03:00
// 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 = h.staticPath + path
_, err := h.staticFS.Open(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
2022-05-03 15:59:47 +03:00
file, err := h.staticFS.Open(h.staticPath + "/" + h.indexPath)
if err != nil {
h.server.notFound(w)
return
}
index, err := ioutil.ReadAll(file)
2022-05-01 13:29:39 +03:00
if err != nil {
h.server.notFound(w)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusAccepted)
w.Write(index)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// get the subdirectory of the static dir
statics, err := fs.Sub(h.staticFS, h.staticPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
2022-05-09 18:20:31 +03:00
http.StripPrefix(h.server.context.config.SubUri, http.FileServer(http.FS(statics))).ServeHTTP(w, r)
2022-05-01 13:29:39 +03:00
}