登录
首页 >  Golang >  Go问答

处理动态 uri 段的 Go net/http 处理函数

来源:stackoverflow

时间:2024-03-25 21:15:44 361浏览 收藏

在 Go 的 net/http 中,使用动态 URI 片段需要使用一个处理程序,该处理程序注册为根路径 "/",并负责分派请求到动态路径。对于静态路径,可以照常使用单独的处理程序进行注册。如果请求路径与任何注册的静态路径不匹配,则会被分派到根处理程序。根处理程序包含代码,用于根据请求路径分派请求,从而支持动态 URI 片段。

问题内容

如何在 go net/http 中使用动态 uri 分段?例如

http.HandleFunc("//", HelloServer)

仅使用 go 内置的 net/http 可以做到这一点吗?


解决方案


为“/”注册一个处理程序并在该处理程序中分派动态路径:

http.handlefunc("/", rootserver)

照常使用静态路径注册其他处理程序:

http.handlefunc("/about", aboutserver)

default server mux 将所有与其他注册路径不匹配的请求分派到为“/”注册的处理程序。在该处理程序中编写代码以在请求路径上分派。这是一个例子:

func rootserver(w http.responsewriter, r *http.request) {
    if r.url.path == "/" {
        indexserver(w, r) // handle root document on site
    } else if uid, fid, ok := matchuserfile(r.url.path), ok {
        userfileserver(w, r, uid, fid)
    } else {
        http.error(w, "not found", http.statusnotfound)
    }
}

函数 matchuserfile 看起来像这样:

func matchUserFile(path string) (uid string, fid string, ok bool) {
    // if path matches the // pattern then 
    //    return user id, file id, true
    // else
    //    return "", "", false
}

matchuserfile 函数的编写方法有很多种。 Regular expressions可能有助于实施。

今天关于《处理动态 uri 段的 Go net/http 处理函数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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