英文:
Execute function before web requests
问题
我正在尝试在每个网络请求之前执行一个函数。我有一个简单的网络服务器:
func h1(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h1")
}
func h2(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h2")
}
func h3(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h3")
}
func main() {
http.HandleFunc("/", h1)
http.HandleFunc("/foo", h2)
http.HandleFunc("/bar", h3)
/*
注册一个在处理程序之前执行的函数,
无论调用什么URL。
*/
http.ListenAndServe(":8080", nil)
}
问题:有没有简单的方法来做到这一点?
英文:
I am trying to execute a function before every web request. I got a simple web server:
func h1(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h1")
}
func h2(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h2")
}
func h3(w http.ResponseWriter, r *http.Request) {
fmt.Pprintf("handler: %s\n", "h3")
}
func main() {
http.HandleFunc("/", h1)
http.HandleFunc("/foo", h2)
http.HandleFunc("/bar", h3)
/*
Register a function which is executed before the handlers,
no matter what URL is called.
*/
http.ListenAndServe(":8080", nil)
}
Question: Is there a simple way to do this?
答案1
得分: 4
将每个HandlerFunc包装起来。
func WrapHandler(f HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 在这里调用任何前置处理函数
mySpecialFunc()
f(w, r)
}
}
http.HandleFunc("/", WrapHandler(h1))
由于在Go语言中函数是一等公民,所以很容易对它们进行包装、柯里化或者其他你想要做的操作。
英文:
Wrap each of your HandlerFuncs.
func WrapHandler(f HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// call any pre handler functions here
mySpecialFunc()
f(w, r)
}
}
http.HandleFunc("/", WrapHandler(h1))
Since Functions are first class values in Go it's easy to wrap them, curry them, or any other thing you may want to do with them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论