1

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?

Adergaard
  • 760
  • 10
  • 24
  • Since the pool is designed to be used concurrently, it's not ultimately a problem. Whether you *want* to use it as a global is another question though: nothing is stopping you from embedding it a struct or just passing a pointer around from main(). – elithrar Jul 26 '14 at 23:26
  • True. Thanks. Also, thanks for the link to your article. – Adergaard Jul 27 '14 at 06:44

1 Answers1

1

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
    }
}
Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • I (as the author of that question!) also wrote an article on how to use the pattern: http://elithrar.github.io/article/custom-handlers-avoiding-globals/ - in most cases you can get away with writing methods on your 'context' type and passing things around that way, but when you need to access the context beyond just method calls, using the struct approach works well (and is idiomatic). – elithrar Jul 27 '14 at 00:51