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

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
主站蜘蛛池模板: 会昌县| 宽甸| 宝鸡市| 大田县| 界首市| 岳西县| 玉山县| 平泉县| 泾阳县| 泰和县| 汉中市| 建瓯市| 西宁市| 兰溪市| 龙州县| 湄潭县| 柏乡县| 大竹县| 新巴尔虎左旗| 高平市| 塔河县| 巧家县| 沽源县| 宁海县| 安化县| 易门县| 都匀市| 左贡县| 离岛区| 宜君县| 达日县| 五莲县| 原阳县| 连云港市| 新安县| 连云港市| 甘南县| 兴和县| 读书| 泾阳县| 上杭县|