Skip to content

Commit

Permalink
catch all fuh real
Browse files Browse the repository at this point in the history
  • Loading branch information
moficodes committed May 20, 2020
1 parent 8aee59e commit 8249085
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"log"
"net/http"
"os"
"path/filepath"

"github.com/gorilla/mux"
_ "github.com/joho/godotenv/autoload"
Expand Down Expand Up @@ -67,7 +69,8 @@ func main() {
api.HandleFunc("/schedule/{accountID}", server.UpdateScheduleHandler).Methods(http.MethodPut)
api.HandleFunc("/schedule/{accountID}", server.DeleteScheduleHandler).Methods(http.MethodDelete)

r.PathPrefix("/").HandlerFunc(serveHTML)
spa := spaHandler{staticPath: "client/build", indexPath: "index.html"}
r.PathPrefix("/").Handler(spa)

port := ":9000"

Expand All @@ -76,6 +79,41 @@ func main() {
log.Fatalln(http.ListenAndServe(port, r))
}

func serveHTML(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "client/build/index.html")
type spaHandler struct {
staticPath string
indexPath string
}

// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
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)

// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
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
}

// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}

0 comments on commit 8249085

Please sign in to comment.