Go using mux Router - How to pass my DB to my handlers

前端 未结 2 498
一整个雨季
一整个雨季 2021-02-07 15:50

At the moment, I try to create a small Web-Project using Go for data handling on the server.

I try to pass my database-connection to my HandlerFunc(tions) but it does no

相关标签:
2条回答
  • 2021-02-07 16:33

    You have three options:

    1. Make your database connection pool a global, so that you don't have to pass it. sql.DB is safe for concurrent access, and this is the easiest approach. The downside is that it makes testing harder and obfuscates "where" the pool is coming from - e.g.

      var db *sql.DB
      
      func main() {
          var err error
          db, err = sql.Open(...)
          // Now accessible globally, no need to pass it around
          // ...
       }
      
    2. Wrap your handlers in a closure, which makes it accessible to the inner handler. You'll need to adapt this to your range-over-routes approach—which is a little obtuse IMO, and makes it harder to see what routes exist, but I digress—for example:

      func SomeHandler(db *sql.DB) http.HandlerFunc {
          fn := func(w http.ResponseWriter, r *http.Request) {
              res, err := db.GetThings()
              // etc.
          }
      
          return http.HandlerFunc(fn)
      }
      
      func main() {
          db, err := sql.Open(...)
          http.HandleFunc("/some-route", SomeHandler(db))
          // etc.
      }
      
    3. Create a custom handler type that accepts a handler - e.g.

      type AppHandler struct {
          Handler func(env *config.Env, w http.ResponseWriter, r *http.Request)
          Env *config.Env
      }
      
      // ServeHTTP allows your type to satisfy the http.Handler interface.
      func (ah *AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
          ah.Handler(ah.Env, w, r)
      }
      
      func SomeHandler(env *config.Env, w http.ResponseWriter, r *http.Request) {
          res, err := env.DB.GetThings()
          // etc.
      }
      

    Note that (shameless plug!) I've written about the last approach in detail, and Alex Edwards has an excellent blog post on approaches to accessing DB pools in Go programs as well.

    The only strict advice I can give is that you should shy away from passing your DB pool around in a request context, which is inefficient and not good practice (request contexts are for temporary, per-request objects).

    0 讨论(0)
  • 2021-02-07 16:41

    You can always have "env" defined as global variable.

    But before everyone will hate me, this is not a good solution! You should create a package that encapsulate the access to your database with public function that state your exact intent.

    Something along the lines of

    Package db
    
    var config ....
    
    func ShowTodos(params ... ) result {
       your database access code here.... 
    }
    

    and from your router function access it with

    db.ShowTodos(...)
    
    0 讨论(0)
提交回复
热议问题