angularjsgotypescriptangularservemux

How to serve a file if URL doesn't match to any pattern in Go?


I'm building a Single Page Application using Angular 2 and Go, and in Angular I use routing. If I open the site at, say, http://example.com/, Go will serve me my index.html file, which is good because I wrote this:

mux.Handle("/", http.FileServer(http.Dir(mysiteRoot)))

Now I have a route in Angular, let's say, /posts, and If it's a default route (that is, when useAsDefault is true) or if I just manually go to http://example.com/posts, I'll get a 404 error from Go, which means that no handler is specified for this path.

I don't think that creating a handler in Go for every single Angular route is a good idea, because there may be a lot of routes. So my question is, how can I serve index.html in Go if the request URL doesn't match any other pattern that I set in my ServeMux?


Solution

  • Well, that was pretty easy actually. The net/http documentation says this:

    Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

    So I needed to do something with my "/" handler. http.FileServer looks for files in a directory that is specified in the pattern string, so I just replaced it with this:

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, mysiteRoot + "index.html")
    })
    

    And it works just fine.