2016-12-08 08:16:43 +00:00
|
|
|
package db
|
2016-11-19 21:35:23 +00:00
|
|
|
|
|
|
|
import (
|
2016-12-11 13:50:01 +00:00
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2016-12-25 15:24:40 +00:00
|
|
|
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
2016-11-19 21:35:23 +00:00
|
|
|
)
|
|
|
|
|
2016-12-08 08:16:43 +00:00
|
|
|
var Conn *sql.DB
|
2016-11-19 21:35:23 +00:00
|
|
|
|
2017-01-09 20:07:41 +00:00
|
|
|
func getDSN() string {
|
2016-12-25 15:24:40 +00:00
|
|
|
var dsn = fmt.Sprintf(
|
|
|
|
"%s:%s@%s/%s",
|
|
|
|
os.Getenv("ANA_DATABASE_USER"),
|
|
|
|
os.Getenv("ANA_DATABASE_PASSWORD"),
|
|
|
|
os.Getenv("ANA_DATABASE_HOST"),
|
|
|
|
os.Getenv("ANA_DATABASE_NAME"),
|
|
|
|
)
|
2017-01-09 20:07:41 +00:00
|
|
|
return dsn
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetupDatabaseConnection opens up & returns a SQL connection
|
|
|
|
func SetupDatabaseConnection() (*sql.DB, error) {
|
|
|
|
var err error
|
2016-11-25 15:30:38 +00:00
|
|
|
|
2017-01-09 20:07:41 +00:00
|
|
|
Conn, err = sql.Open("mysql", getDSN())
|
2016-12-11 13:50:01 +00:00
|
|
|
if err != nil {
|
2016-12-11 14:37:51 +00:00
|
|
|
return nil, err
|
2016-12-11 13:50:01 +00:00
|
|
|
}
|
2016-11-19 21:35:23 +00:00
|
|
|
|
2016-12-11 14:37:51 +00:00
|
|
|
// Open doesn't open a connection right away. Validate DSN by calling Ping().
|
2016-12-11 13:50:01 +00:00
|
|
|
err = Conn.Ping()
|
|
|
|
if err != nil {
|
2016-12-11 14:37:51 +00:00
|
|
|
return nil, err
|
2016-12-11 13:50:01 +00:00
|
|
|
}
|
2016-11-21 12:24:50 +00:00
|
|
|
|
2016-12-11 14:37:51 +00:00
|
|
|
return Conn, nil
|
2016-11-19 21:35:23 +00:00
|
|
|
}
|