1 回答
TA贡献2019条经验 获得超9个赞
您可以创建一个 (func) 类型,它ServeHTTP可以完成您需要的所有操作,然后在内部调用原始函数,然后将您的处理程序转换为该类型:
package main
import (
"fmt"
"log"
"net/http"
)
type wrappedHandler func(w http.ResponseWriter, r *http.Request)
func (h wrappedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println("Do Other GAE Stuff")
h(w, r)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi!")
}
func main() {
http.Handle("/", wrappedHandler(handler))
http.ListenAndServe(":8080", nil)
}
如果要将某些内容传递给handler()功能,可以将其添加到签名中,例如:
type wrappedHandler func(w http.ResponseWriter, r *http.Request, conn *db.Connection)
func (h wrappedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn := db.CreateConnection();
h(w, r, conn)
}
func handler(w http.ResponseWriter, r *http.Request, conn *db.Connection) {
data := conn.AllTheData()
fmt.Fprintf(w, data)
}
- 1 回答
- 0 关注
- 220 浏览
添加回答
举报