-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
71 lines (60 loc) · 1.2 KB
/
main.go
File metadata and controls
71 lines (60 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"time"
"github.com/go-sql-driver/mysql"
)
var (
username, password, host, port string
timeout int
)
func init() {
username = getenv("USERNAME", "root")
password = getenv("PASSWORD", "")
host = getenv("HOST", "mysql")
port = getenv("PORT", "3306")
var err error
timeout, err = strconv.Atoi(getenv("TIMEOUT", "60"))
if err != nil {
timeout = 60
}
mysql.SetLogger(log.New(ioutil.Discard, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile))
}
func main() {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/", username, password, host, port))
if err != nil {
fmt.Printf("Unexpected error: %s\n", err)
os.Exit(1)
}
defer db.Close()
t := 1
for t < timeout {
t += 1
err = db.Ping()
if err != nil {
switch err.(type) {
case *mysql.MySQLError:
default:
fmt.Print(".")
time.Sleep(1 * time.Second)
continue
}
}
fmt.Printf("Connected.\n")
os.Exit(0)
}
fmt.Printf("\nOperation timed out in %d seconds.\n", timeout)
os.Exit(1)
}
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}