登录
首页 >  Golang >  Go问答

Golang 处理函数

来源:stackoverflow

时间:2024-02-12 11:30:26 225浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Golang 处理函数》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

所以我遇到了一个奇怪的问题,有些路线可以工作,有些则不行。我将首先向您展示我的主要功能,然后举例说明问题所在。

func main() {
    http.HandleFunc("/", home)
    http.HandleFunc("/project", project)
    http.HandleFunc("/about", about)
    http.HandleFunc("/contact", contact)

    http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./assets"))))

    err := http.ListenAndServe(":80", nil)
    if err != nil {
        fmt.Println("ListendAndServe doesn't work : ", err)
    }
}

例如,路由“/contact/”不起作用,当我运行此代码并转到 localhost/contact 时,它会将我发送到主页。但是,当我将 handlefunc 中的路由更改为“/contactos”,然后转到 localhost/contactos 时,它确实可以工作。

另一个例子,“/project”现在可以工作,但是当我将其更改为“/projects”时,它就不起作用了。


正确答案


请注意,如果您注册 /project/ (注意结尾斜杠),则 /project//project 都将起作用(带或不带尾斜杠)。如果您注册 /project (没有尾部斜杠),则只有 /project 可以工作,/project/ 将由根处理程序 / 匹配。

引用自http.ServeMux

查看相关问题:

How to map to the same function with a pattern that ends with or with "/" with http.HandleFunc

终于介绍完啦!小伙伴们,这篇关于《Golang 处理函数》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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