justinas / alice

Painless middleware chaining for Go

Home Page:https://godoc.org/github.com/justinas/alice

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dependency Injection Support?

danhardman opened this issue · comments

Is there any way I can inject a dependency such as a *sql.DB or something into my middleware?

I want to be able to verify session users and user roles that require access to a database. It makes sense to add this logic to the middleware, but I'm struggling to wrap my head around how it would work.

Any suggestions?

I would do something like this:

type server struct {
  db *sql.db
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // handle request here, with access to the database using `s.db`.
}

srv := new(server)
var db *sql.db // TODO: setup database connection etc.
srv.db = db
chain := alice.New().Then(srv)

But this isn't specific to Alice.

Yeah sorry I realised what I could do as soon as I posted it. Thanks!