golang 每日一庫之 urfave-negroni
urfave/negroni 是一個輕量級的、可擴展的 Go 中間件庫,專爲構建 HTTP 服務而設計。
它的核心理念是中間件棧(Middleware Stack),可以像洋蔥一樣一層層包裹處理請求,非常適合構建具有清晰請求生命週期的 Web 應用或 API。
GitHub 地址:https://github.com/urfave/negroni
特點
-
中間件機制清晰簡潔
:支持多箇中間件,按順序執行
-
兼容
http.Handler接口:能無縫接入標準庫或其他框架(如 Gorilla Mux)
-
支持中間件鏈式調用和終止
-
自帶常用中間件
:Recovery、Logger、Static 等
-
極易擴展
:只需實現
negroni.Handler接口
安裝
go get github.com/urfave/negroni
快速🌰
package main
import (
"fmt"
"net/http"
"github.com/urfave/negroni"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from Negroni!")
})
n := negroni.New()
n.Use(negroni.NewLogger()) // 日誌中間件
n.Use(negroni.NewRecovery()) // 恢復 panic 的中間件
n.UseHandler(mux) // 最終處理器
http.ListenAndServe(":3000", n)
}
自定義中間件
Negroni 的中間件需要實現以下接口:
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request, http.HandlerFunc)
}
自定義一個簡單的中間件:
type MyMiddleware struct{}
func (m *MyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
fmt.Println("Before request")
next(w, r)
fmt.Println("After request")
}
註冊:
n := negroni.New()
n.Use(&MyMiddleware{})
常用內置中間件
與其他配合使用
配合 Gorilla Mux 使用:
r := mux.NewRouter()
r.HandleFunc("/api", handler)
n := negroni.Classic() // 包含 Logger, Recovery
n.UseHandler(r)
http.ListenAndServe(":3000", n)
舉🌰:添加認證中間件
type AuthMiddleware struct{}
func (a *AuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
token := r.Header.Get("Authorization")
if token != "secret-token" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
第三方兼容中間件
以下是兼容 Negroni 的中間件列表,如果你也有兼容 Negroni 的中間件,如果想提交自己的中間件,建議你附上 PR 鏈接。
總結
Negroni 是 Go 生態中最早也是最經典的中間件框架之一,它強調中間件鏈、簡潔可插拔,非常適合用於理解中間件機制或構建簡單項目。
性能上不及 Echo、Gin。
讀完源碼之後,開發中間件基本上就不是難題了。
標題:golang 每日一庫之 urfave/negroni
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/06/12/1749712902825.html
聯繫:scotttu@163.com
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/qUVSeYDB_zH2op2dLCg5HQ