That is one way of doing it, Another, is to use structs as your dependency injection tool.
Example:
type AppConnection struct {
Client *mongo.Client
IsConnected bool
// and some other things that you need such as schemas etc..
}
func (ac AppConnection) Connect() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
ac.IsConnected = false
return
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
ac.IsConnected = false
return
}
ac.IsConnected = true
ac.Client = client
fmt.Println("Connected to MongoDB!")
}
Now why this is good is you can pass around your pointer of AppConnection struct in other modules of your code without worrying about circular dependency while import.