- Go Web Development Cookbook
- Arpit Aggarwal
- 197字
- 2021-08-27 19:01:14
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:
- Install github.com/gorilla/mux using the go get command, as follows:
$ go get github.com/gorilla/mux
- 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)
}
- Run the program with the following command:
$ go run http-server-gorilla-mux-routing.go
推薦閱讀
- 社交網絡對齊
- RCNP實驗指南:構建高級的路由互聯網絡(BARI)
- 計算機網絡與數據通信
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 世界互聯網發展報告·2019
- 雷達饋線技術
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- Spring 5.0 Projects
- 夢工廠之材質N次方:Maya材質手冊
- Android UI Design
- 人際網絡
- 網絡空間作戰:機理與籌劃
- 賽博空間簡史
- Hands-On Full Stack Web Development with Aurelia
- 計算機網絡(項目教學版)