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

How to do it…

In this recipe, we will use gorilla/mux to define a few routes, like we did in our previous recipe, along with their handlers or resources. As we have already seen in one of our previous recipes, to use external packages, first we have to install the package using the go get command or we have to copy it manually to $GOPATH/src or $GOPATH. We will do the same in the recipe as well. Perform the following steps:

  1. Install github.com/gorilla/mux using the go get command, as follows:
$ go get github.com/gorilla/mux
  1. Create http-server-gorilla-mux-routing.go and copy the following content:
package main
import
(
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
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!"))
}
)
var PathVariableHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("Hi " + name))
}
)
func main()
{
router := mux.NewRouter()
router.Handle("/", GetRequestHandler).Methods("GET")
router.Handle("/post", PostRequestHandler).Methods("POST")
router.Handle("/hello/{name}",
PathVariableHandler).Methods("GET", "PUT")
http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
}
  1. Run the program with the following command:
$ go run http-server-gorilla-mux-routing.go
主站蜘蛛池模板: 北宁市| 南郑县| 宿州市| 泽普县| 油尖旺区| 土默特左旗| 襄垣县| 昭苏县| 阳西县| 新巴尔虎右旗| 如东县| 兴隆县| 鱼台县| 北辰区| 民权县| 南开区| 金昌市| 松溪县| 陆丰市| 伊通| 来安县| 左贡县| 四平市| 孟州市| 潜江市| 八宿县| 丽江市| 龙口市| 高平市| 高清| 虞城县| 宜兰县| 文水县| 白朗县| 靖西县| 宁陵县| 三门县| 乌拉特中旗| 尚义县| 阿瓦提县| 墨江|