如何使用Gorilla/mux获取不含实际参数的路由路径?
解决方案
Gorilla/mux 原生支持获取路由定义的原始模板路径,具体实现方式如下:
获取当前匹配的路由对象
使用mux.CurrentRoute(req)方法,传入请求对象*http.Request,即可拿到当前请求匹配到的mux.Route实例。提取路由模板
调用该路由实例的GetPathTemplate()方法,就能得到你定义时带参数变量的路径模板(比如/organizations/{orgId}/projects/{projectId})。
示例代码
可以在日志中间件中集成该逻辑:
func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 获取当前匹配的路由 route := mux.CurrentRoute(r) if route != nil { // 提取原始路由模板 templatePath, err := route.GetPathTemplate() if err == nil { // 使用模板路径记录日志 log.Printf("请求模板路径: %s, 请求方法: %s", templatePath, r.Method) } } next.ServeHTTP(w, r) }) } // 注册中间件并定义路由 func main() { r := mux.NewRouter() r.Use(LoggingMiddleware) subr := r.PathPrefix("/v1").Subrouter() subr.Handle("/organizations/{orgId}/projects/{projectId}", CreateProject()).Methods(http.MethodPost) http.ListenAndServe(":8080", r) }
注意事项
- 若请求未匹配到任何路由,
mux.CurrentRoute(r)会返回nil,需做非空判断避免空指针错误。 - 带
PathPrefix的子路由,GetPathTemplate()会返回完整的模板路径(比如示例中会返回/v1/organizations/{orgId}/projects/{projectId}),与路由定义一致。
内容的提问来源于stack exchange,提问作者cbll
相关产品推荐
相关产品推荐

