Search code examples
httpgourlgorillamux

Serve default page for all subdirs of URL


I would like to call FileServer in such way, that it serves the same page for all subdirectories of distinct directories (subdirs).

The naïve approach, of course, does not work:

  for _, prefix := range subdirs {
     fsDist := http.FileServer(http.Dir(defaultPage))
     r.PathPrefix(prefix).Handler(http.StripPrefix(prefix, fsDist))
  }

Because /abc/123 is mapped to defaultPage/123 and I need just defaultPage.

For example, if subdirs := []string{"abc", "xyz"}, it should be mapped like this:

    abc/xyz => defaultPage
    abc/def => defaultPage
    xyz/aaa => defaultPage

I understand that I need something like http.SetPrefix or something like that, but there is nothing of that kind. Of course, I could write my own handler, but I wonder what is the standard approach here?

The task is pretty common, and I suppose there should be some standardized approach?


Solution

  • EDIT: multiple-route support & static file-serving:


    It sounds like you just want:

    r := mux.NewRouter()
    r.HandleFunc("/products", ProductsHandler) // some other route...
    
    staticFilePath := "catch-all.txt"
    
    fh := http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, staticFilePath)
        },
    )
    
    for _, dir := range []string{"abc", "xyz"} {
        r.PathPrefix("/" + dir + "/").Handler(fh)
    }
    

    Working example (run outside playground): https://play.golang.org/p/MD1Tj1CUcEh

    $ curl localhost:8000/abc/xyz
    catch all
    
    $ curl localhost:8000/abc/def
    catch all
    
    $ curl localhost:8000/xyz/aaa
    catch all
    
    $ curl localhost:8000/products
    product