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

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
主站蜘蛛池模板: 保定市| 高州市| 新源县| 沐川县| 乐亭县| 含山县| 辽中县| 惠东县| 迁安市| 都昌县| 石嘴山市| 盐源县| 金华市| 商南县| 枣阳市| 南华县| 双城市| 清新县| 呈贡县| 本溪市| 长春市| 邓州市| 什邡市| 昔阳县| 靖宇县| 夏邑县| 德格县| 水城县| 贵阳市| 那坡县| 定日县| 凤庆县| 游戏| 来凤县| 咸宁市| 平阴县| 宣城市| 兴和县| 环江| 金沙县| 紫金县|