Captain Hook - Web hook server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

128 lines
2.7 KiB

package main
import (
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
)
func connectDB() (*sql.DB, error) {
// Get user credentials
user, exists := os.LookupEnv("MYSQL_USER")
checkExists(exists, "Couldn't find database user")
password, exists := os.LookupEnv("MYSQL_PASSWORD")
checkExists(exists, "Couldn't find database password")
// Get database params
dbServer, exists := os.LookupEnv("MYSQL_SERVER")
checkExists(exists, "Couldn't find database server")
dbPort, exists := os.LookupEnv("MYSQL_PORT")
checkExists(exists, "Couldn't find database port")
dbName, exists := os.LookupEnv("MYSQL_DATABASE")
checkExists(exists, "Couldn't find database name")
connectionString := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s",
user,
password,
dbServer,
dbPort,
dbName,
)
// Check how many times to try the db before quitting
attemptsStr, exists := os.LookupEnv("DB_ATTEMPTS")
if !exists {
attemptsStr = "5"
}
attempts, err := strconv.Atoi(attemptsStr)
if err != nil {
attempts = 5
}
timeoutStr, exists := os.LookupEnv("DB_CONNECTION_TIMEOUT")
if !exists {
timeoutStr = "5"
}
timeout, err := strconv.Atoi(timeoutStr)
if err != nil {
timeout = 5
}
db, err = sql.Open("mysql", connectionString)
if err != nil {
return db, err
}
for i := 1; i <= attempts; i++ {
//// DEBUG: Making sure table is good
// if err := dropDB(db); err != nil {
// log.Fatal(err)
// }
// Create database if it doesn't exist
err = createDB(db)
if err != nil {
// Check to see if the error is a connection issue
if !strings.HasPrefix(err.Error(), "dial") {
return db, err
}
if i != attempts {
log.Printf(
"WARNING: Could not connect to db on attempt %d. Trying again in %d seconds.\n",
i,
timeout,
)
} else {
return db, errors.Errorf("Could not connect to db after %d attempts\n", attempts)
}
time.Sleep(time.Duration(timeout) * time.Second)
} else {
// No error to worry about
break
}
}
log.Println("Connection to db succeeded!")
return db, nil
}
// func queryRow(db *sql.DB, name string) (*sql.Rows, error) {
// b, err := ioutil.ReadFile(name)
// if err != nil {
// return nil, err
// }
// return db.QueryRow(string(b)), nil
// }
// func query(db *sql.DB, name string) (interface{}, error) {
// db.Qu
// }
func execSQL(db *sql.DB, name string) error {
b, err := ioutil.ReadFile(name)
if err != nil {
return err
}
statement, err := db.Prepare(string(b))
if err != nil {
return err
}
statement.Exec()
return nil
}
func createDB(db *sql.DB) error {
return execSQL(db, "sql/setup.sql")
}
func dropDB(db *sql.DB) error {
return execSQL(db, "sql/drop.sql")
}