Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@clairew
Last active August 9, 2018 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clairew/7a03f07800f2e45201cbe33ef47f266e to your computer and use it in GitHub Desktop.
Save clairew/7a03f07800f2e45201cbe33ef47f266e to your computer and use it in GitHub Desktop.
DB Connection Helper Function Example
//GetTestDBConnection returns DB pointer to be used in test suite
func GetTestDBConnection() *sql.DB, error {
testDbName, sqlDriver := GenerateTestDB() // wrapped logic that generates test db and tables
dbUser, dbPass, dbHost, dbPort := GetDBCredsFromConfig() // get necessary db credentials
log.Info("Initializing test database connection")
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, testDbName)
db, err := sql.Open(sqlDriver, connectionString)
if err != nil {
log.WithFields(log.Fields{ // use logrus logging package to specify error and scenario
"err": err,
"dbName": testDbName,
}).Warn("Unable to establish test database connection")
return nil, err
}
return db, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment