duanmu5039 2017-10-23 02:29
浏览 79
已采纳

golang http:如何将请求路由到处理程序

I'm newbie on Golang and have a simple question about building a web server.

Saying that my web server has users so the users can change their names and their passwords. Here is how I design the URLs:

/users/Test         GET
/users/Test/rename       POST   newname=Test2
/users/Test/newpassword  POST   newpassword=PWD

The first line is to show the information of the user named Test. The second and the third is to rename and to reset password.

So I'm thinking that I need to use some regular expression to match the HTTP requests, things like http.HandleFunc("/users/{\w}+", controller.UsersHandler).

However, it doesn't seem that Golang supports such a thing. So does it mean that I have to change my design? For example, to show the information of the user Test, I have to do /users GET name=Test?

  • 写回答

2条回答 默认 最新

  • duanjiushu5063 2017-10-23 07:04
    关注

    You may want to run pattern matching on r.URL.Path, using the regex package (in your case you may need it on POST) This post shows some pattern matching samples. As @Eugene suggests there are routers/http utility packages also which can help.

    Here's something which can give you some ideas, in case you don't want to use other packages:

    In main:

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果