我在创建将链接到其他路由并需要访问数据库的中间件时遇到问题,我不确定如何解决此问题。处理需要访问数据库的中间件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)。在采取任何进一步措施之前,您至少应该能够阅读方法签名。此外,我不会为所有请求设置相同的“超级”上下文。 –