在此示例中, Redigo Doc for Pool redis池是在func main中设置为全局变量。这是一个犹太人的方式来做事吗?如果你真的要左右使用全局变量,还是有更好的方法来完成同样的事情? 我见过唯一的其他解决方案,例如在将上下文传递给接口方法中:
创建一个接受嵌入式上下文和我们的处理函数的 struct type,并且感谢 ServeHTTP 。我们仍然满足 http.Handler 接口。
在你的情况下, struct 会包含 pool code>处理函数函数。 $ $ p $ type appContext struct { 池池 类型appHandler结构{ * appContext h func(a * appContext,w http.ResponseWriter,r * http.Request) (int,error)} func(ah appHandler)ServeHTTP(w http.Respons eWriter,r * http.Request){ ... } func main(){ context:=& appContext { pool:..., //任何其他数据} }
In the example here Redigo Docs for Pool the redis pool is set as a global variable in func main. Is that a kosher way to do things? Should you really be using global varibales left and right or is there a better, more preferred way of accomplishing the same thing?
解决方案The only other solution have I seen, for instance in "Passing Context to Interface Methods" is:
create a struct that accepts an embedded context and our handler type, and we still satisfy the http.Handler interface thanks to ServeHTTP.
In your case, the struct would include the pool, and the handler function.
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 } }
更多推荐
Redigo Redis Pool是否应该是一个全球变量?
发布评论