Reputation: 12431
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
?
Upvotes: 4
Views: 9839
Reputation: 1782
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")
}
Upvotes: 6
Reputation: 12875
Unfortunately standard http router not to savvy. There are 2 ways:
Manually check methods, urls and extract usernames.
Use routers from other packages like https://github.com/gorilla/mux
gorilla mix, echo gin-gonic etc
Upvotes: 0