gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:43:22 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to Handle dynamic URL in Golang [closed]

(2 个回答)



How to create route which is dynamic

(1 个回答)


2年前关闭。




我如何在 Go net/http 中使用动态 uri 段?例如

http.HandleFunc("/<user_id>/<file_id>", HelloServer)

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

最佳答案

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

 http.HandleFunc("/", RootServer)

像往常一样使用静态路径注册其他处理程序:
 http.HandleFunc("/about", AboutServer)

default server mux将所有与其他注册路径不匹配的请求分派(dispatch)到为“/”注册的处理程序。在该处理程序中编写代码以在请求路径上分派(dispatch)。这是一个例子:
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 /<user_id>/<file_id> pattern then
// return user id, file id, true
// else
// return "", "", false
}

有多种写法 matchUserFile功能。 Regular expressions可能有助于实现。

关于Go net/http 处理函数与动态 uri 段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60746977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com