登录
首页 >  Golang >  Go问答

代码的有效性为何会受到行的影响?

来源:stackoverflow

时间:2024-03-25 14:36:39 206浏览 收藏

在使用 Go 语言的 HTTP 路由器时,代码行的顺序会影响有效性。顺序不当会导致错误的路由行为,例如重定向或返回意外的响应。虽然代码本身看起来正确,但顺序的调整却导致了不同的结果,这表明浏览器缓存中可能存在问题。

问题内容

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)

请求“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))

结果没有变化。

这是为什么呢? “地图”这个词有什么魔力?


正确答案


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

到这里,我们也就讲完了《代码的有效性为何会受到行的影响?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>