go - What is the best way to have dependency injection in Golang -


i'm beginner in golang , i'm working on small library need db connection @ point in code différent sub package / method call. i'm wondering how can manage ?

example, if manage have webserver, works handler, how can connection inside function ? used process, simple method call or mvc model ?

i don't want use global because me it's bad practice except if it's exceptional way (or tricky somehow).

i read lot of write in different website, still, i'm asking , learning different opinion , experiences.

thanks time !

create struct represent resource​, let's call cart. add , post methods struct. these methods should http handlers. in main create instance of struct db interface. , in route call cart.get. in method have access db interface.

not working example, idea of injecting testing.

type storage interface {     preparecontext(context.context, string) (*sql.stmt, error) }  func main() {     db, _ := sql.open("mysql", `querystring`)     http.handlefunc("/", cart{db}.get)     http.listenandserve(":8080", nil) }  type cart struct {     storage }  func (crt cart) get(w http.responsewriter, r *http.request) {     q, _ := crt.preparecontext(context.background(), `select *`)     fmt.println(q.exec()) }  /////////test type testdb struct{}  func (c testdb) preparecontext(context.context, string) (*sql.stmt, error) {     return nil, nil } func testget(t *testing.t) {     db := testdb{}     _ = cart{db}      //http test here } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -