Fix static file server

This commit is contained in:
Ken Hibino 2021-01-05 15:36:12 -08:00
parent 22df9d1332
commit b572b76a0b

36
main.go
View File

@ -2,11 +2,11 @@ package main
import ( import (
"embed" "embed"
"errors"
"fmt" "fmt"
"io" "io/fs"
"log" "log"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"time" "time"
@ -21,7 +21,7 @@ import (
// path to the index file within that static directory are used to // path to the index file within that static directory are used to
// serve the SPA in the given static directory. // serve the SPA in the given static directory.
type staticFileServer struct { type staticFileServer struct {
staticContents embed.FS contents embed.FS
staticDirPath string staticDirPath string
indexFileName string indexFileName string
} }
@ -39,26 +39,30 @@ func (srv *staticFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
if path == "/" { if path == "/" {
path = filepath.Join(srv.staticDirPath, srv.indexFileName) path = srv.indexFilePath()
} else { } else {
path = filepath.Join(srv.staticDirPath, path) path = filepath.Join(srv.staticDirPath, path)
} }
f, err := srv.staticContents.Open(path) bytes, err := srv.contents.ReadFile(path)
// If path is error (e.g. file not exist, path is a directory), serve index file.
var pathErr *fs.PathError
if errors.As(err, &pathErr) {
bytes, err = srv.contents.ReadFile(srv.indexFilePath())
}
if err != nil { if err != nil {
status := http.StatusInternalServerError
if os.IsNotExist(err) {
status = http.StatusNotFound
}
http.Error(w, err.Error(), status)
return
}
defer f.Close()
if _, err := io.Copy(w, f); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
if _, err := w.Write(bytes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (srv *staticFileServer) indexFilePath() string {
return filepath.Join(srv.staticDirPath, srv.indexFileName)
} }
const ( const (
@ -139,7 +143,7 @@ func main() {
api.HandleFunc("/redis_info", newRedisInfoHandlerFunc(rdb)).Methods("GET") api.HandleFunc("/redis_info", newRedisInfoHandlerFunc(rdb)).Methods("GET")
fs := &staticFileServer{ fs := &staticFileServer{
staticContents: staticContents, contents: staticContents,
staticDirPath: "ui/build", staticDirPath: "ui/build",
indexFileName: "index.html", indexFileName: "index.html",
} }