我在創建將鏈接到其他路由並需要訪問數據庫的中間件時遇到問題,我不確定如何解決此問題。處理需要訪問數據庫的中間件Go
我將所有的應用程序上下文都存儲在一個名爲AppContext
的結構中。我想創建一個函數處理程序,它看起來是這樣的:
func SomeHandler(appC *AppContext, next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Access the database using appC.db
// Logic that requires access to the database.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
在main.go
,我曾嘗試:
someHandler := middleware.SomeHandler(&appC)
但是,我得到的錯誤not enough arguments in call to middleware.SomeHandler
。解決這個問題最好的辦法是什麼?
順便說一句,你可以使用這個中間件上下文在圍棋,https://golang.org/pkg/context/的事情,讓appContext名字可能會讓人困惑。 –
坦率地說:閱讀文檔和[參觀](https://tour.golang.org/welcome/1)。在採取任何進一步措施之前,您至少應該能夠閱讀方法簽名。此外,我不會爲所有請求設置相同的「超級」上下文。 –