英文:
Get the current pattern that matched an http.HandleFunc
问题
有没有办法获取触发http.HandleFunc
的当前路由?类似这样的方式吗?
http.HandleFunc("/foo/", serveFoo)
func serveFoo(rw http.ResponseWriter, req *http.Request) {
fmt.Println(http.CurrentRoute())
// 应该打印出"/foo/"
}
我想要获取当前路由的原因是因为我经常写这样的代码。
if req.URL.Path != "/some-route/" {
http.NotFound(resp, req)
return
}
// 或者
key := req.URL.Path[len("/some-other-route/"):]
如果代码能更容易复制粘贴、模块化和DRY(Don't Repeat Yourself),那就更好了。
if req.URL.Path != http.CurrentRoute() {
http.NotFound(resp, req)
return
}
// 或者
key := req.URL.Path[http.CurrentRoute():]
这只是一个小问题,所以我不想在我的项目中引入一个完整的依赖(Gorilla Mux)。
英文:
Is there a way to get the current route that triggered an http.HandleFunc
? Maybe something like this?
http.HandleFunc("/foo/", serveFoo)
func serveFoo(rw http.ResponseWriter, req *http.Request) {
fmt.Println(http.CurrentRoute())
// Should print "/foo/"
}
The reason I want to get the current route is because I find myself writing code like this often.
if req.URL.Path != "/some-route/" {
http.NotFound(resp, req)
return
}
// or
key := req.URL.Path[len("/some-other-route/"):]
It would be nice if the code was a bit more copy-pastable, modular, and DRY like this.
if req.URL.Path != http.CurrentRoute() {
http.NotFound(resp, req)
return
}
// or
key := req.URL.Path[http.CurrentRoute():]
This is really just a small thing, so I'd rather not bring a whole other dependency into my project (Gorilla Mux).
答案1
得分: 1
无法获取匹配的当前路由,但可以在您的场景中消除重复的代码。编写一个处理程序,在调用另一个处理程序之前检查路径:
func HandleFuncExact(mux *http.ServeMux, pattern string, handler func(http.ResponseWriter, *http.Request)) {
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if req.URL.Path != pattern {
http.NotFound(w, r)
return
}
handler(w, r)
})
}
在您的应用程序中,调用包装函数而不是HandleFunc
:
HandleFuncExact(http.DefaultServeMux, "/some-route/", serveSomeRoute)
函数serveSomeRoute
可以假设路径完全是"/some-route/"
。
英文:
It is not possible to get the current route that matched, but it is possible to eliminate the duplicate code in your scenario. Write a handler that checks the path before calling through to another handler:
func HandleFuncExact(mux *http.ServeMux, pattern string, handler func(http.ResponseWriter, *http.Request) {
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if req.URL.Path != pattern {
http.NotFound(w, r)
return
}
handler(w, r)
})
}
In your application, call the wrapper instead of HandlFunc:
HandleFuncExact(http.DefaultServeMux, "/some-route/", serveSomeRoute)
The function serveSomeRoute
can assume that the path is exactly "/some-route/".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论