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)
}
}
Try browsing to http://localhost:9080/some/other/path
This works fine if the StripPrefix does not have the / after /some/
That said: the strange behavior is: I notice with the above code (including
the slash after /some/ in StripPrefix) that browsing to
http://localhost:9080/some/other/path results in a 404 and effectively a
redirect to http://localhost:9080/other/path - the browser's URL changes to
the version of the path without the prefix!
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
https://github.com/paralin
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/65819ada-a15a-45d9-b88b-85e6e988b6f1n%40googlegroups.com.