Skip to content

Commit

Permalink
properly intercept not found requests for single page app
Browse files Browse the repository at this point in the history
When a request comes in for an unknown path looking for an HTML content
type, we need to render the index.html page so that the single page app
can do its thing.
  • Loading branch information
bgentry committed May 3, 2024
1 parent f3ffa19 commit 2fddf1e
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ func initAndServe(ctx context.Context) int {
logger.ErrorContext(ctx, "error getting frontend index", slog.String("error", err.Error()))
return 1
}
httpFS := http.FS(frontendIndex)
fileServer := http.FileServer(httpFS)
serveIndex := serveFileContents("index.html", httpFS)

dbPool, err := getDBPool(ctx, dbURL)
if err != nil {
Expand Down Expand Up @@ -87,7 +90,7 @@ func initAndServe(ctx context.Context) int {
mux.HandleFunc("GET /api/workflows/{id}", handler.WorkflowGet)
mux.HandleFunc("GET /api/states", handler.StatesAndCounts)
mux.HandleFunc("/api", http.NotFound)
mux.Handle("/", http.FileServer(http.FS(frontendIndex)))
mux.Handle("/", intercept404(fileServer, serveIndex))

logHandler := sloghttp.Recovery(mux)
config := sloghttp.Config{
Expand Down
73 changes: 73 additions & 0 deletions spa_response_writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"fmt"
"net/http"
"strings"
)

func intercept404(handler, on404 http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hookedWriter := &spaResponseWriter{ResponseWriter: w}
handler.ServeHTTP(hookedWriter, r)

if hookedWriter.got404 {
on404.ServeHTTP(w, r)
}
})
}

func serveFileContents(file string, files http.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

Check failure on line 21 in spa_response_writer.go

View workflow job for this annotation

GitHub Actions / Go lint

parameter name 'w' is too short for the scope of its usage (varnamelen)
// Restrict only to instances where the browser is looking for an HTML file
if !strings.Contains(r.Header.Get("Accept"), "text/html") {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 not found")

return
}

// Open the file and return its contents using http.ServeContent
index, err := files.Open(file)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "%s not found", file)

return
}

fi, err := index.Stat()

Check failure on line 39 in spa_response_writer.go

View workflow job for this annotation

GitHub Actions / Go lint

variable name 'fi' is too short for the scope of its usage (varnamelen)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "%s not found", file)

return
}

w.Header().Set("Content-Type", "text/html; charset=utf-8")
http.ServeContent(w, r, fi.Name(), fi.ModTime(), index)
}
}

type spaResponseWriter struct {
http.ResponseWriter
got404 bool
}

func (srw *spaResponseWriter) WriteHeader(status int) {
if status == http.StatusNotFound {
// Don't actually write the 404 header, just set a flag.
srw.got404 = true
} else {
srw.ResponseWriter.WriteHeader(status)
}
}

func (hrw *spaResponseWriter) Write(p []byte) (int, error) {

Check failure on line 66 in spa_response_writer.go

View workflow job for this annotation

GitHub Actions / Go lint

ST1016: methods on the same type should have the same receiver name (seen 1x "hrw", 1x "srw") (stylecheck)
if hrw.got404 {
// No-op, but pretend that we wrote len(p) bytes to the writer.
return len(p), nil
}

return hrw.ResponseWriter.Write(p)
}

0 comments on commit 2fddf1e

Please sign in to comment.