(摘) 用 Go 语言实现一个 HTTP 中间件

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

原文地址

一个基础的中间件示例

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)
}

相关文章