Hi all,
I was very confused by the behavior I was seeing while testing a simple program with http.StripPrefix:
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/other/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path)
w.WriteHeader(200)
w.Write([]byte("\n\nSeen path: " + r.URL.Path + "\n"))
})
// adding a / after /some/ here causes the strange redirect
prefixHandler := http.StripPrefix("/some/", mux)
// Start the HTTP server with the stripPrefixHandler
err := http.ListenAndServe(":9080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path)
prefixHandler.ServeHTTP(w, r)
}))
if err != nil {
panic(err)
}
}
This works fine if the StripPrefix does not have the / after /some/
Why is the http handler returning a redirect to the stripped version?
< HTTP/1.1 301 Moved Permanently
< Content-Type: text/html; charset=utf-8
< Location: /other/path
< Date: Wed, 20 Dec 2023 00:37:00 GMT
< Content-Length: 46
<
<a href="/other/path">Moved Permanently</a>.
I would expect to instead see a 404 with the given path /some/other/path.
This seems like a bug or otherwise undocumented behavior, the docs just say "StripPrefix handles a request for a path that doesn't begin
with prefix by replying with an HTTP 404 not found error."
Thanks,
Christian Stewart