官术网_书友最值得收藏!

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:

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:

Let's understand the code changes we made in this recipe:

  1. 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!"))
}
)
  1. 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))
}
)
  1. 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)
}
主站蜘蛛池模板: 崇左市| 汝城县| 开江县| 桐庐县| 三亚市| 于都县| 名山县| 民勤县| 新巴尔虎左旗| 遂川县| 凤城市| 治县。| 昌平区| 莱阳市| 巴塘县| 银川市| 枝江市| 温州市| 周口市| 明星| 偏关县| 青田县| 富蕴县| 高碑店市| 鄢陵县| 渝中区| 呈贡县| 藁城市| 滦平县| 历史| 高雄市| 习水县| 蓝山县| 临猗县| 凭祥市| 扎兰屯市| 互助| 锦州市| 金川县| 宝应县| 革吉县|