这种事情通常是用Go中的 中间件 完成的。最简单的例子是:
package mainimport ( "fmt" "html" "log" "net/http")func main() { http.HandleFunc("/", handler) http.HandleFunc("/foo", middleware(handler)) log.Fatal(http.ListenAndServe(":8080", nil))}func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))}func middleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { r.URL.Path = "/MODIFIED" // Run the next handler next.ServeHTTP(w, r) }}如您所见,中间件是具有以下功能的函数:
- 接受一个
http.HandlerFunc
参数 - 返回一个
http.HandlerFunc
; - 调用
http.handlerFunc
传入的。
通过这种基本技术,您可以根据需要“链接”许多中间件:
http.HandleFunc("/foo", another(middleware(handler)))这种模式有一些变体,大多数Go框架使用的语法略有不同,但是概念通常是相同的。



