V
V
VladimirDronik2020-09-18 22:10:26
go
VladimirDronik, 2020-09-18 22:10:26

How to pass database connection information to golang package?

How, from the point of view of the architecture of the application on GO, to pass a database connection to all packages where it will be used?

Let's say now I do in the main package:

db, err := sql.Open("mysql", "database:[email protected](127.0.0.1:3306)/database?parseTime=true")


and I pass the connection to the servers package, then I pass the connection to the servers
servers.SocketsRun(db)

package to the connect package
connect.run(db)

, and so on along the chain ...

And how is it correct, from the point of view of architecture, to use the established connection to the database in all packages?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
VladimirDronik, 2020-09-18
@VladimirDronik

Would this option be correct?
https://fooobar.com/questions/10380979/sharing-ag...

E
Evgeny Samsonov, 2020-09-18
@bitniks

You can use Dependency Injection by passing the database connection to the struct instantiation function

type Server struct {
    db *sql.DB
}

func NewServer(db *sql.DB) *Server {
    return &Server{
        db: db,
    }
}

func (s *Server) Run() {
    // s.db 
}

R
Risent Veber, 2020-10-01
@risentveber

Use DI and IoC
Run-time: https://github.com/uber-go/dig
Compile-time: https://github.com/google/wire

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question