为什么相同的代码在不同的行上能够工作或者不能工作?

huangapple go评论90阅读模式
英文:

Why does the same code work or not for different lines?

问题

muxMaps := http.NewServeMux()
muxMaps.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("地图页面")) })

mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("主页面")) })
mux.Handle("/maps/", http.StripPrefix("/maps", muxMaps))
mux.Handle("/maps1/", http.StripPrefix("/maps1", muxMaps))

http.ListenAndServe(":8000", mux)

请求"http://localhost:8000/"返回"主页面"

请求"http://localhost:8000/maps1/"返回"地图页面"

但是请求"http://localhost:8000/maps/"会重定向到"http://localhost:8000/"并返回"主页面"

好的,也许顺序很重要。我尝试这样做:

mux.Handle("/maps1/", http.StripPrefix("/maps1", muxMaps))
mux.Handle("/maps/", http.StripPrefix("/maps", muxMaps))

结果没有改变。

为什么会这样?"maps"这个词有什么特殊之处?

英文:
muxMaps := http.NewServeMux()
muxMaps.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {w.Write([]byte("maps page"))})

mux := http.NewServeMux()
mux.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {w.Write([]byte("main page"))})
mux.Handle("/maps/", http.StripPrefix("/maps", muxMaps))
mux.Handle("/maps1/", http.StripPrefix("/maps1", muxMaps))

http.ListenAndServe(":8000", mux)

Request "http://localhost:8000/" returns "main page"

Request "http://localhost:8000/maps1/" returns "maps page"

But the request "http://localhost:8000/maps/" redirects to "http://localhost:8000/" and returns "main page"

Ok, maybe the order matters. I try this:

mux.Handle("/maps1/", http.StripPrefix("/maps1", muxMaps))
mux.Handle("/maps/", http.StripPrefix("/maps", muxMaps))

And the result is unchanged.

Why is that? What's the magic for the word "maps"?

答案1

得分: 1

问题实际上出在浏览器缓存中。

英文:

The problem really was in the browser cache.

huangapple
  • 本文由 发表于 2023年4月6日 17:03:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75947690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定