我正在尝试在每个 Web 请求之前执行一个功能。我有一个简单的网络服务器:
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)
}
问题:有没有一种简单的方法可以做到这一点?