我是 Golang 的新手,有一个关于构建 Web 服务器的简单问题。
说我的网络服务器有用户,所以用户可以更改他们的名字和密码。以下是我设计 URL 的方式:
/users/Test GET
/users/Test/rename POST newname=Test2
/users/Test/newpassword POST newpassword=PWD
第一行显示名为Test
的用户信息。第二个和第三个是重命名和重置密码。
所以我想我需要使用一些正则表达式来匹配 HTTP 请求,比如 http.HandleFunc("/users/{\w}+", controller.UsersHandler)
.
不过,Golang好像不支持这样的东西。那么这是否意味着我必须改变我的设计?例如,要显示用户Test
的信息,我必须做/users GET name=Test
?
最佳答案
您可能希望使用正则表达式包在 r.URL.Path 上运行模式匹配(在您的情况下,您可能需要在 POST 上使用它)This post显示一些模式匹配样本。正如@Eugene 所建议的那样,路由器/http 实用程序包也可以提供帮助。
这里有一些东西可以给你一些想法,以防你不想使用其他包:
主要是:
http.HandleFunc("/", multiplexer)
...
func multiplexer(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
getHandler(w, r)
case "POST":
postHandler(w, r)
}
}
func getHandler(w http.ResponseWriter, r *http.Request) {
//Match r.URL.path here as required using switch/use regex on it
}
func postHandler(w http.ResponseWriter, r *http.Request) {
//Regex as needed on r.URL.Path
//and then get the values POSTed
name := r.FormValue("newname")
}
关于http - 戈朗 http : how to route requests to handlers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881150/