Nested ServeMux always returns "301 Moved Permanently"
Edit: to make testing easier in Firefox, I disabled caching.. otherwise I would have to manually clear cache to get accurate results. I did not seem to have this same issue when using Chrome, though.
Keep in mind I am new to Go but this issue was driving me crazy... I was experiencing the same exact behavior that you are (obviously)..
It would seem Go/http is picky about how patterns are formatted..
I messed with this for about an hour and was finally able to get a working example using the following code:
// Working Code
package main
import "net/http"
func main() {
root := http.NewServeMux()
api := http.NewServeMux()
api.HandleFunc("/ping", myHandlerFunc)
root.Handle("/api/", http.StripPrefix("/api", api))
http.ListenAndServe(":8080", root)
}
func myHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong\n"))
}
I tried as many different configurations as you can imagine (as far as /
forward slashes are concerned) and the above code was the only way I could get it to work..
Specifically referring to:
// Leading forward slash on /ping
api.HandleFunc("/ping", myHandlerFunc)
// The first /api/ is surrounded in forward slashes,
// the second /api only contains a leading forward slash
root.Handle("/api/", http.StripPrefix("/api", api))
Changing the code to this causes 404's...
// DOES NOT WORK!!
package main
import "net/http"
func main() {
root := http.NewServeMux()
api := http.NewServeMux()
api.HandleFunc("/ping", myHandlerFunc)
root.Handle("/api", http.StripPrefix("/api", api))
http.ListenAndServe(":8080", root)
}
func myHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong\n"))
}
I hope this helps in some way! Cheers