-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
80 lines (69 loc) · 1.44 KB
/
database.go
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
72
73
74
75
76
77
78
79
80
package database
import (
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
var (
// Database wrapper
DB *sqlx.DB
)
type Databases struct {
Type string
MySQL MySQLInfo
SQLite SQLiteInfo
}
// MySQLInfo is the details for the database connection
type MySQLInfo struct {
Username string
Password string
Name string
Hostname string
Port int
Parameter string
}
// SQLiteInfo is the details for the database connection
type SQLiteInfo struct {
Parameter string
}
// DSN returns the Data Source Name
func DSN(ci MySQLInfo) string {
// Example: root:@tcp(localhost:3306)/test
return ci.Username +
":" +
ci.Password +
"@tcp(" +
ci.Hostname +
":" +
fmt.Sprintf("%d", ci.Port) +
")/" +
ci.Name + ci.Parameter
}
// Connect to the database
func Connect(d Databases) {
var err error
switch d.Type {
case "MySQL":
// Connect to MySQL
if DB, err = sqlx.Connect("mysql", DSN(d.MySQL)); err != nil {
log.Println("SQL Driver Error", err)
}
// Check if is alive
if err = DB.Ping(); err != nil {
log.Println("Database Error", err)
}
case "SQLite":
// Connect to SQLite
if DB, err = sqlx.Connect("sqlite3", d.SQLite.Parameter); err != nil {
log.Println("SQL Driver Error", err)
}
// Check if is alive
if err = DB.Ping(); err != nil {
log.Println("Database Error", err)
}
default:
log.Println("No registered database in config")
}
}