http - 戈朗 http : how to route requests to handlers

标签 http go

我是 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/

相关文章:

linux - Linux 上的 Indy HTTP 服务器仅返回响应文本的最后一个字符

javascript - 使用(客户端)Javascript 修改 HTTP 响应 header

ruby-on-rails - 在 Rails 应用程序中处理大文件上传的最佳方法是什么?

go - 使用其他功能的mongodb连接

go - 主机名 :51813 中的无效字符 "\r"

image-processing - Golang 中的卷积

go - 为什么在尝试构建任何Go程序时出现重新声明的错误?

python - 我很难从我的 python 程序上传数据到地下天气

sql - 从SQL响应读取uniqueidentifier问题

php - 如何在php中获取http请求来源