Someone may ask what is so special about serving single-page applications? Well, if you use hash (#) based URL’s like <em></em> , there is no problem because browser recognize that this is a default page with some parameters and doesn’t make another request to the server. However, if you want to use non-hash based routes, there is a problem if you try to refresh a non-default route. In this case browser’s default action is to load such URL from the server and there is no such document on the server. For example, if you load your SPA at URL <em></em> and then you click on another route, you will see in your browser’s URL field something like <em></em> . That works fine unless you try to reload the page. In that case browser doesn’t know this is actually already loaded SPA, but it actually tries to fetch /yourroute URI from server. As there is no such URI on the server, you will usually get the famous 404 error and your application breaks.

In order to overcome this, your server should always return index.html or whatever document is default for your single-page application. Maybe not literally in all cases, maybe you want to use some patterns, but in lot of cases you actually want to return index.html in all 404 cases so that your SPA can continue normal execution. JavaScript based Web server usually have such options because they are very often used to serve SPA’s, for example sirv-cli has option –single which will solve the problem. But can we do this in Go based server?

Go’s standard library includes http.FileServer handler which can serve static files. However, it doesn’t have possibility to override 404’s with some default document. You can make a handler which first checks if requested URI (file) exists on the server and if not, respond with index.html, but this involves additional file system check which you may want to avoid for performance reasons. The question is, how can we solve this without additional filesystem check?

We can write our own implementation of http.ResponseWriter interface which will intercept 404 errors and respond with index.html in such cases. Let’s see such an implementation:

 1type intercept404 struct {
 2	http.ResponseWriter
 3	statusCode int
 6func (w *intercept404) Write(b []byte) (int, error) {
 7	if w.statusCode == http.StatusNotFound {
 8		return len(b), nil
 9	}
10	if w.statusCode != 0 {
11		w.WriteHeader(w.statusCode)
12	}
13	return w.ResponseWriter.Write(b)
16func (w *intercept404) WriteHeader(statusCode int) {
17	if statusCode >= 300 && statusCode < 400 {
18		w.ResponseWriter.WriteHeader(statusCode)
19		return
20	}
21	w.statusCode = statusCode

The idea is to replace original http.ResponseWriter when invoking http.FileServer with the one above and in case of 404, replace the requested URI with index.html (actually /) and invoke http.FileServer again, but now with original http.ResponseWriter. Here is the http.HandlerFunc which implements this idea:

 1func spaFileServeFunc(dir string) func(http.ResponseWriter, *http.Request) {
 2	fileServer := http.FileServer(http.Dir(dir))
 3	return func(w http.ResponseWriter, r *http.Request) {
 4		wt := &intercept404{ResponseWriter: w}
 5		fileServer.ServeHTTP(wt, r)
 6		if wt.statusCode == http.StatusNotFound {
 7			r.URL.Path = "/"
 8			w.Header().Set("Content-Type", "text/html")
 9			fileServer.ServeHTTP(w, r)
10		}
11	}

Finally, here is the main function which implements the server itself:

1func main() {
2	http.HandleFunc("/", spaFileServeFunc("public"))
4	log.Fatal(http.ListenAndServe(":3006", nil))

The full implementation using Svelte as JavaScript frontend can be found here .

Someone may argue that we still have performance loses in case that document is not found in initial request, but this is again more or less just file system check. This is still better than doing the double file system check in all requests.