Why this happens: 1. http.StripPrefix chang reuqest's path from /some/other/path to other/path 2. ServerMux.Handler will return 301 when cleanPath(r.URL.Path) != r.URL.Path
Link: https://github.com/golang/go/blob/go1.21.5/src/net/http/server.go#L2467 This seems to be a issue with ServerMux, Our prefix cannot end with / when we use StripPrefix with ServerMux. 在2023年12月20日星期三 UTC+8 08:38:29<Christian Stewart> 写道: > 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 golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2eca6b78-49c6-4be2-b55d-f49d118b8e6fn%40googlegroups.com.