gorilla/mux請求路由和分發(fā)的 Go 框架
gorilla/mux 實(shí)現(xiàn)了一個(gè)請求路由和分發(fā)的 Go 框架。
mux 名字的意思是 "HTTP request multiplexer". 和標(biāo)準(zhǔn)包 http.ServeMux類似, mux.Router根據(jù)已注冊路由列表匹配傳入請求,并調(diào)用與URL或其他條件匹配的路由的處理程序。
主要特性:
- It implements the
http.Handlerinterface so it is compatible with the standardhttp.ServeMux. - Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
- URL hosts, paths and query values can have variables with an optional regular expression.
- Registered URLs can be built, or "reversed", which helps maintaining references to resources.
- Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
安裝
go get -u github.com/gorilla/mux
代碼示例
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}
這里我們注冊了三個(gè) URL 匹配路由進(jìn)行處理。路徑也可以是變量:
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
這些名稱用于創(chuàng)建路由變量的映射,可以通過調(diào)用mux.Vars 獲?。?/p>
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
}
評論
圖片
表情
