您可以通过按名称查找路由并使用 Route.URL 生成 url 来“反转” gorilla/mux url
您需要命名您的路线,以便您可以通过Router.Get 轻松查找它。
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
一旦你有了路由,你就可以通过将参数传递给 URL 来构建一个 url
url, err := r.Get("article").URL("category", "technology", "id", "42")
// "/articles/technology/42"
请注意,如果您希望自动插入主机,则需要在您的路由中定义它:
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
// url.String() will be "http://news.domain.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")