【发布时间】:2018-04-13 11:44:38
【问题描述】:
我有一个使用 gorilla mux 的服务器。现在我有两个这样的处理程序:
api.HandleFunc("/foo", logHandler(mypackage.fooHandler)).Methods("GET")
api.HandleFunc("/bar", logHandler(mypackage.barHandler)).Methods("GET")
现在我想创建一个计算请求的通用方法 (logHandler)。现在我有这样的东西:
func logHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// what to do here???
}
}
我可以从 logHandler 函数中的请求 (r) 中获取所有必要的信息,但是我需要返回什么?我如何让它发挥作用?
【问题讨论】:
-
不需要返回任何东西,因为
http.HandlerFunc被定义为没有返回参数,只要确保在返回的http.HandlerFunc中调用传入的处理函数fn。例如。fn(w, r)。 play.golang.org/p/ugqZp1vBz5B -
只计算你的请求。
-
考虑使用
r.Use()安装中间件。 -
以防万一您想使用 prometheus:violetear.org/post/prometheus