reprogl
1package container2
3import (4"database/sql"5"log"6"time"7
8"github.com/doug-martin/goqu/v9"9_ "github.com/doug-martin/goqu/v9/dialect/mysql"10_ "github.com/go-sql-driver/mysql"11)
12
13func (app *Application) SetupDatabase() error {14db, err := getDBConnection(app.InfoLog)15if err != nil {16return err17}18
19app.DB = db20goqu.SetTimeLocation(time.Local)21
22return nil23}
24
25func getDBConnection(logger *log.Logger) (db *sql.DB, err error) {26var i int27
28for i < 5 {29logger.Print("Trying to connect to the database")30db, err = openDB(cnf.DatabaseDSN)31if err == nil {32logger.Print("The database is connected")33
34return35} else {36logger.Print(err)37}38
39i++40time.Sleep(1000 * time.Millisecond)41}42
43return nil, err44}
45
46func openDB(dsn string) (*sql.DB, error) {47db, err := sql.Open("mysql", dsn)48if err != nil {49return nil, err50}51
52if err = db.Ping(); err != nil {53return nil, err54}55
56return db, nil57}
58