英文:
How do I print the url path without parameters?
问题
我正在使用Gorilla/mux创建一个RESTful API,它在路径中使用参数。我创建的代码如下:
r := mux.NewRouter()
subr := r.PathPrefix("/v1").Subrouter()
subr.Handle("/organizations/{orgId}/projects/{projectId}", CreateProject()).Methods(http.MethodPost)
然而,当捕获请求并记录结果时,我不想记录如下内容:
/organizations/fff-555-aaa9999/projects/amazing-project
这是从解析r *http.Request.URL
值得到的结果。
相反,我想要获取初始路由器值/organizations/{orgId}/projects/{projectId}
,这样我就可以在日志中从那里进行过滤。
使用gorilla/mux,有没有一种方法可以获取路由路径而不包含实际参数,而是参数变量呢?
英文:
I have a RESTful API using Gorilla/mux. It is parameterized in the path. I am creating it as such:
r := mux.NewRouter()
subr := r.PathPrefix("/v1").Subrouter()
subr.Handle("/organizations/{orgId}/projects/{projectId}", CreateProject()).Methods(http.MethodPost)
However, when capturing the request and logging the outcome, I don't want to log i.e.
/organizations/fff-555-aaa9999/projects/amazing-project
which is what I'd get from parsing the r *http.Request.URL
value.
Instead, I'd like to get the initial router value of /organizations/{orgId}/projects/{projectId}
so I can filter from that in my logging.
Using gorilla/mux, is there a way to get the router path without the actual parameters, but the parameter variables instead?
答案1
得分: 3
在CreateProject
函数内部,你可以使用以下代码:
func CreateProject(w http.ResponseWriter, r *http.Request) {
path, _ := mux.CurrentRoute(r).GetPathTemplate()
fmt.Println(path)
}
英文:
Inside CreateProject
function you coud use this:
func CreateProject(w http.ResponseWriter, r *http.Request) {
path, _ := mux.CurrentRoute(r).GetPathTemplate()
fmt.Println(path)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论