一个基础的中间件示例
package main
import (
"fmt"
"net/http"
)
func middleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Executing middleware before request phase!")
// 将控制权交回 Handler
handler.ServeHTTP(w, r)
fmt.Println("Executing middleware after response phase!")
})
}
func mainLogic(w http.ResponseWriter, r *http.Request) {
// 业务逻辑
fmt.Println("Executing mainHandler...")
w.Write([]byte("OK")) } func main() {
// HandlerFunc 返回 HTTP Handler
mainLogicHandler := http.HandlerFunc(mainLogic)
http.Handle("/", middleware(mainLogicHandler))
http.ListenAndServe(":8000", nil)
}