Dependency Injection Support?
danhardman opened this issue · comments
Dan Hardman commented
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?
Thomas de Zeeuw commented
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.
Dan Hardman commented
Yeah sorry I realised what I could do as soon as I posted it. Thanks!