Go 中的路由器 - 在每个 http 请求之前运行一个函数

Moh*_*iba 3 routes go

我将 Go 与 http 一起使用,如下所示:

mux := http.NewServeMux()
mux.HandleFunc("/API/user", test)
mux.HandleFunc("/authAPI/admin", auth)
Run Code Online (Sandbox Code Playgroud)

我想在每个 http 请求之前运行一个函数,更好的是,在每个包含 /authAPI/ 的请求上运行一个函数。
我怎样才能在 Go 中实现这一目标?

Not*_*fer 6

除了 @Thomas 提出的建议之外,您可以将整个多路复用器包装在您自己的多路复用器中,该多路复用器在调用任何处理程序之前调用,并且可以仅调用其自己的处理程序。这就是 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)
    }))
}
Run Code Online (Sandbox Code Playgroud)