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条)

报告相同问题?