如何打印URL路径而不包含参数?

huangapple go评论135阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2023年3月14日 16:49:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75730850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定