This is Database config file.config.go
type Database struct {
conn *sql.DB
}
// global db instance
var (
dbInstance *Database
dbOnce sync.Once
)
// creates a new database instance if not exist
// otherwise return the existing instance
func GetDBInstance() *Database {
dbOnce.Do(func() {
// Capture connection properties.
cfg := mysql.Config{
User: "root",
Passwd: "***********",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "go_microservices",
}
// creates a pool of connection
// not the actual database connection
conn, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Error().Msg(fmt.Sprintf("database connection error %s", err))
SendInterruptSignal()
return
}
// ping the database
// to check if the database connection is alive
pingErr := conn.Ping()
if pingErr != nil {
log.Error().Msg(fmt.Sprintf("ping error %s", pingErr))
SendInterruptSignal()
return
}
// creates a new instance of DB
dbInstance = &Database{conn: conn}
log.Info().Msg("Successfully Connected To The Database")
})
return dbInstance
}
I'm trying to use that dbInstance in my handler but i'm not able to access the conn property of the instance
func (p *Product) AllProducts() []*Product {
db := database_config.GetDBInstance()
fmt.Printf("db: %#v\n", db)
// db1 := database_config.GetDBInstance()
// if db == db1 {
// fmt.Printf("db: %#v\n", db)
// fmt.Printf("db1: %#v\n", db1)
// } else {
// fmt.Print("not same")
// }
return nil
}
when i print the object in the console. I can see the conn property in the database instance
db: &database_config.Database{conn:(*sql.DB)(0xc0002b81a0)}
When i directly return the connection. I can acess every property of db connnection but when i create a new database object with the connection. I'm not able to access anything