英文:
Is Redigo Redis Pool really supposed to be a global variable?
问题
在这个例子中Redigo文档中的Pool,Redis连接池被设置为main
函数中的全局变量。这样做的方式是否合适?你真的应该随意使用全局变量吗?还是有更好、更推荐的方法来完成同样的事情?
英文:
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?
答案1
得分: 1
我看到的唯一其他解决方案是在"Passing Context to Interface Methods"中,例如:
创建一个接受嵌入式上下文和我们的
handler
类型的struct
,通过ServeHTTP
方法仍然满足http.Handler
接口。
在你的情况下,这个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: ...,
// 其他数据
}
}
英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论