1 回答

TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
查看 Negroni 中間件。它讓您通過不同的中間件和自定義 HandlerFuncs 傳遞您的 HTTP 請求。像這樣的東西:
n := negroni.New(
negroni.NewRecovery(),
negroni.HandlerFunc(myMiddleware),
negroni.NewLogger(),
negroni.NewStatic(http.Dir("public")),
)
...
...
func myMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Logging on the way there...")
if r.URL.Query().Get("password") == "secret123" {
next(rw, r) //**<--------passing the request to next middleware/func**
} else {
http.Error(rw, "Not Authorized", 401)
}
log.Println("Logging on the way back...")
}
注意如何next(rw,r)用于傳遞 HTTP 請求
如果您不想使用 Negroni,您可以隨時查看它的實現(xiàn),了解它如何將 HTTP 請求傳遞給另一個中間件。
它使用自定義處理程序,看起來像:
handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
參考:https : //gobridge.gitbooks.io/building-web-apps-with-go/content/en/middleware/index.html
- 1 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報