路由 gorilla/mux 包的基本使用
安装依赖
$ go get -u github.com/gorilla/mux
使用 gorilla/mux
func main() {
router := mux.NewRouter()
// 定义请求路径,方法,已经路由名称
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<h1>Hello,欢迎来到goblog!</h1>")
}).Methods("GET").Name("home")
router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about")
// 设置路由匹配miss的响应规则
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
// 设置中间件
router.Use(forceHTMLMiddleware)
// 获取 路由home 的url
homeURL, _ := router.Get("home").URL()
http.ListenAndServe(":3000", removeTrailingSlash(router))
}
由于 gorilla/mux 的路由解析采用的是 精准匹配 规则,所以访问 http://localhost:3000/about/
时返回404,因为无法匹配末尾的斜杠
// 去除路径末尾的反斜杠
func removeTrailingSlash(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
}
next.ServeHTTP(w, r)
})
}
func forceHTMLMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
next.ServeHTTP(w, r)
})
}
本作品采用《CC 协议》,转载必须注明作者和本文链接