Consider the example below. This example is an evolution from this Stack Overflow answer where a nested http.ServeMux is used to handle requests under a given path:
package main
import (
"net/http"
)
func main() {
rootMux := http.NewServeMux()
rootMux.Handle("/", writeHandler("root mux"))
rootMux.Handle("/top_path/", http.StripPrefix("/top_path", subHandler()))
http.ListenAndServe(":8080", rootMux)
}
func subHandler() http.Handler {
subMux := http.NewServeMux()
subMux.Handle("/", writeHandler("sub mux"))
subMux.Handle("/sub_path", writeHandler("sub path"))
return subMux
}
func writeHandler(message string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(message))
})
}
When running this example and sending a request to localhost:8080, you will get root mux in the response, as you would expect. When making a request to localhost:8080/top_path (without the trailing slash), you will also get the expected response of sub mux. The one difference this time however is that the request was actually redirected to localhost:8080/top_path/ (with a trailing slash).
This trailing-slash redirection behavior is described in the http package documentation.
So my question is this: Is there no way to have a nested mux, such as subMux that can handle both top_path (without trailing slash and no redirect) and anything under it, e.g. /top_path/sub_path? If rootMux is able to handle requests to localhost:8080 without redirecting to localhost:8080/, then shouldn't there be a way for subMux to be able to handle requests to localhost:8080/top_path without redirecting to localhost:8080/top_path/?