在此处的示例Redigo Docs forPool中,redis池在funcmain中设置为全局变量。这是一种洁净的做事方式吗?您是否应该真正在左右使用全局变量,或者是否有更好,更优选的方法来完成同一件事?
我看到的唯一其他解决方案例如在“将上下文传递给接口方法”中是:
创建一个struct接受嵌入式上下文和我们的handler类型的,并且http.Handler由于,我们仍然满足该接口ServeHTTP。
struct
handler
http.Handler
ServeHTTP
在您的情况下,struct将包括pool和handler功能。
pool
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 } }