![Go Web Development Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/993/36699993/b_36699993.jpg)
上QQ阅读APP看书,第一时间看更新
How it works…
Once we run the program, the HTTP server will start locally listening on port 8080, and accessing http://localhost:8080/, http://localhost:8080/post, and http://localhost:8080/hello/foo from a browser or command line will produce the message defined in the corresponding handler definition. For example, execute http://localhost:8080/ from the command line, as follows:
$ curl -X GET -i http://localhost:8080/
This will give us the following response from the server:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/5dbedcdd-3be8-4718-af12-a6d8afb02094.png?sign=1738855659-SFt6JHc3QypCx6yEg2bE66VThjZh4lqH-0-cb48d2d0b24a3c1b821ea7dbcd44bdb2)
We could also execute http://localhost:8080/hello/foo from the command line, as follows:
$ curl -X GET -i http://localhost:8080/hello/foo
This will give us the following response from the server:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/783a091d-58e2-406d-b4ac-18bb23bc2aed.png?sign=1738855659-EdtFOJsnF6T4kuq7Ces60ylBuuVlnvYt-0-d34ebd0e532539360446c119c72946e6)
Let's understand the code changes we made in this recipe:
- First, we defined GetRequestHandler and PostRequestHandler, which simply write a message on an HTTP response stream, as follows:
var GetRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("Hello World!"))
}
)
var PostRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("It's a Post Request!"))
}
)
- Next, we defined PathVariableHandler, which extracts request path variables, gets the value, and writes it to an HTTP response stream, as follows:
var PathVariableHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("Hi " + name))
}
)
- Then, we registered all these handlers with the gorilla/mux router and instantiated it, calling the NewRouter() handler of the mux router, as follows:
func main()
{
router := mux.NewRouter()
router.Handle("/", GetRequestHandler).Methods("GET")
router.Handle("/post", PostCallHandler).Methods("POST")
router.Handle("/hello/{name}", PathVariableHandler).
Methods("GET", "PUT")
http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
}