Go 从零开始(三)路由器 gorilla/mux
HttpRouter 速度快,但是功能单一。
gorilla/mux 功能比较丰富。
一、下载安装
执行 go get -u github.com/gorilla/mux
二、定义映射到程序的路由
1、请求的 URL 精确匹配到路由时,执行对应的程序。
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}
2、匹配变量,可以用正则匹配
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
在程序中用 mux.Vars() 取得路由中的变量
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
}
3、匹配域名
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler).Host("www.example.com")
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler).Host("{subdomain:[a-z]+}.example.com")
4、匹配路由前缀
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler).PathPrefix("/products/")
5、匹配请求方式
r.HandleFunc("/products", ProductsHandler).
Host("www.example.com").
Methods("GET")
6、匹配域名类型 http、https 等
r.HandleFunc("/products", ProductsHandler).
Host("www.example.com").
Methods("GET").
Schemes("http")
7、匹配 Header 信息
r.Headers("X-Requested-With", "XMLHttpRequest")
r.HeadersRegexp("Content-Type", "application/(text|json)")
8、自定义匹配规则
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
return r.ProtoMajor == 0
})
三、路由分组
相同域名的路由分组 ↓
r := mux.NewRouter()
s := r.Host("www.example.com").Subrouter()
s.HandleFunc("/products/", ProductsHandler)
s.HandleFunc("/products/{key}", ProductHandler)
s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
相同前缀的路由分组 ↓
r := mux.NewRouter()
s := r.PathPrefix("/products").Subrouter()
// "/products/"
s.HandleFunc("/", ProductsHandler)
// "/products/{key}/"
s.HandleFunc("/{key}/", ProductHandler)
// "/products/{key}/details"
s.HandleFunc("/{key}/details", ProductDetailsHandler)
四、路由命名
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
用 name 获取上面定义的路由(/articles/technology/42
)
url, err := r.Get("article").URL("category", "technology", "id", "42")
获取 host 和 path
// "http://news.example.com/"
host, err := r.Get("article").URLHost("subdomain", "news")
// "/articles/technology/42"
path, err := r.Get("article").URLPath("category", "technology", "id", "42")
五、中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
// 路由中追加中间件
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)
六、URL 最后面的斜线处理
URL 后面有没有斜线,都希望匹配到相同路由。
调用 StrictSlash(value bool) 函数。
router := mux.NewRouter().StrictSlash(true)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异