在这里的例子Redigo Docs for Pool中,redis池被设置为func main中的全局变量。这是一种犹太人的做事方式吗?你真的应该左右使用全局变量,还是有更好,更优选的方法来完成同样的事情?
答案 0 :(得分:1)
我见过的唯一其他解决方案,例如“Passing Context to Interface Methods”是:
创建一个
struct
,接受嵌入的上下文和我们的handler
类型,由于http.Handler
,我们仍然满足ServeHTTP
界面。
在您的情况下,struct
会包含pool
和handler
功能。
type appContext struct {
pool Pool
}
type appHandler struct {
*appContext
h func(a *appContext, w http.ResponseWriter, r *http.Request) (int, error)
}
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
...
}
func main() {
context := &appContext{
pool: ...,
// any other data
}
}