Go 中的路由器 - 运行 每个 http 请求之前的函数
router in Go - run a function before each http request
我将 Go 与 http 一起使用,如下所示:
mux := http.NewServeMux()
mux.HandleFunc("/API/user", test)
mux.HandleFunc("/authAPI/admin", auth)
并且我想 运行 在每个 http 请求之前执行一个函数
更好的是,运行 每个包含 /authAPI/ 的请求的函数。
我怎样才能在 Go 中实现这一目标?
你可以只写一个包装函数:
func wrapHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// ...
// do something
// ...
handler(w, req)
}
}
并像这样使用它:
mux.HandleFunc("/authAPI/admin", wrapHandlerFunc(auth))
运行 据我所知,不支持给定 URL 树(子路由器,用 mux
的说法)下的所有内容。
在@Thomas 提议的基础上,您可以将整个 mux 包装在您自己的 mux 中,该 mux 在调用任何处理程序之前调用,并且可以只调用它自己的处理程序。这就是在 go 中实现替代 http 路由器的方式。示例:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Handled %s", r.RequestURI)
}
func main(){
// this will do the actual routing, but it's not mandatory,
// we can write a custom router if we want
mux := http.NewServeMux()
mux.HandleFunc("/foo", handler)
mux.HandleFunc("/bar", handler)
// we pass a custom http handler that does preprocessing and calls mux to call the actual handler
http.ListenAndServe(":8081", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){
fmt.Fprintln(w, "Preprocessing yo")
mux.ServeHTTP(w,r)
}))
}
我将 Go 与 http 一起使用,如下所示:
mux := http.NewServeMux()
mux.HandleFunc("/API/user", test)
mux.HandleFunc("/authAPI/admin", auth)
并且我想 运行 在每个 http 请求之前执行一个函数
更好的是,运行 每个包含 /authAPI/ 的请求的函数。
我怎样才能在 Go 中实现这一目标?
你可以只写一个包装函数:
func wrapHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// ...
// do something
// ...
handler(w, req)
}
}
并像这样使用它:
mux.HandleFunc("/authAPI/admin", wrapHandlerFunc(auth))
运行 据我所知,不支持给定 URL 树(子路由器,用 mux
的说法)下的所有内容。
在@Thomas 提议的基础上,您可以将整个 mux 包装在您自己的 mux 中,该 mux 在调用任何处理程序之前调用,并且可以只调用它自己的处理程序。这就是在 go 中实现替代 http 路由器的方式。示例:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Handled %s", r.RequestURI)
}
func main(){
// this will do the actual routing, but it's not mandatory,
// we can write a custom router if we want
mux := http.NewServeMux()
mux.HandleFunc("/foo", handler)
mux.HandleFunc("/bar", handler)
// we pass a custom http handler that does preprocessing and calls mux to call the actual handler
http.ListenAndServe(":8081", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){
fmt.Fprintln(w, "Preprocessing yo")
mux.ServeHTTP(w,r)
}))
}