2 ms·
I've actually built out a concept to address this: https://github.com/infogulch/inject https://github.com/infogulch/inject Call `di := inject.New(db, logger, t
by infogulch 10y ago
I've actually built out a concept to address this: https://github.com/infogulch/inject https://github.com/infogulch/inject
Call `di := inject.New(db, logger, tmpl, ...)` then you can call `di.Inject(myfunction)` which just calls the function with the values passed to New and returns the result.
"YAWN"
Here's the key: `myfunction` shouldn't just execute, it should return a closure over the injected values that can be called later. E.g.
func home(t *template.Template, db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
var tm string
db.QueryRow(`select datetime('now')`).Scan(&tm)
t.ExecuteTemplate(w, "home.html", tm)
}
}
Now with `fn := di.Inject(home)`, fn is a plain old http.HandlerFunc, it has access to its' dependencies (and just those dependencies) without global state, and there is no reflection in the hot path.
Of course, you could use this technique manually: `fn := home(tmpl, db)` but inject can be integrated with your framework and you don't have to make any changes to code. It's also designed to not require the framework to depend on the reflect package, it can just define and accept the Inject interface.