Serve Static Files with SPA Fallback
Serve a built frontend from disk, fall back to index.html for extensionless routes, and return 404 for missing assets.
Code
package main
import (
"fmt"
"net/http"
"os"
"path"
)
func SPAHandler(root http.FileSystem) http.Handler {
files := http.FileServer(root)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cleaned := path.Clean("/" + r.URL.Path)
if cleaned != "/" {
file, err := root.Open(cleaned)
if err == nil {
info, statErr := file.Stat()
_ = file.Close()
if statErr != nil || info.IsDir() {
r.URL.Path = "/"
}
} else if path.Ext(cleaned) == "" {
r.URL.Path = "/"
}
}
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "public, max-age=300")
files.ServeHTTP(w, r)
})
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Println("serving dist on port", port)
_ = http.ListenAndServe(":"+port, SPAHandler(http.Dir("dist")))
}
Inside the snippet
Serve Static Files with SPA Fallback is built around the functions SPAHandler and main.
The code reads PORT from the environment at startup.
Using it
The main signature, verbatim, is func SPAHandler(root http.FileSystem) http.Handler
The demo output is labeled (serving dist on port), so the printed lines read as a trace of the operations that ran.
Execute the file and main walks through SPAHandler, in that order.
Key statements
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Println("serving dist on port", port)
_ = http.ListenAndServe(":"+port, SPAHandler(http.Dir("dist")))
}
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- What does Serve Static Files with SPA Fallback print when run?
- Running the file directly is enough — expect labeled output lines such as `serving dist on port`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.