Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang http: how to route requests to handlers

Tags:

http

go

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?

like image 289
Yves Avatar asked Oct 17 '25 15:10

Yves


1 Answers

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")
}
like image 181
Ravi R Avatar answered Oct 20 '25 06:10

Ravi R