What is the "correct" way to handle commonly used dependencies?

Written by
Link to Post

https://www.reddit.com/r/golang/comments/awom9r/what_is_the_correct_way_to_handle_commonly_used/ by 

What is the best practices/idiomatic/correct way to handle the following:

Say you’re writing a web service, in it there is a session and some database client needed across many handlers.

  1. Is there anything wrong with creating a package level variable say SessionStore or DBManager that implements a Store or Manager interface and can be used anywhere in the project? These would be initialized at runtime with the appropriate implementations and configuration.

  2. Would the previous example be fine with exception of an unexported package level variable set explicitly by some package function eg func SetStore(s Store){ sessionStore = s} in the individual packages that need them. “Injected” if you will.

  3. Should there be some middleware high up the chain to add a reference to the requisite dependencies into the request Context? These could be then be referenced down the chain as needed.

  4. Should every handler be explicitly given, as an argument, a reference to the necessary dependencies?

  5. Should handlers be part of a larger struct that holds a reference to the necessary dependencies?

  6. Are all of these ok and I’m obsessing about nothing?

  7. Did I omit the actual correct example? (learning opportunity!)

submitted by /u/br0keit
[link] [comments]

Article Tags:
· ·
Article Categories:

Comments are closed.