在此处的示例Redigo Docs for Pool中,redis池在func main中设置为全局变量。这是一种洁净的做事方式吗?您是否应该真正在左右使用全局变量,或者是否有更好,更优选的方法来完成同一件事?

最佳答案

我看到的唯一其他解决方案,例如在“Passing Context to Interface Methods”中是:



在您的情况下,struct将包括poolhandler函数。

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
    }
}

10-08 04:44