forked from JGSU-open-source-community/go-home
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
69 lines (55 loc) · 1.38 KB
/
init.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
package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/astaxie/beego/config" // refercen beego config parser
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
var (
dbType string
user string
password string
host string
port string
databaseName string
dns string
conf, _ = config.NewConfig("ini", "app.conf")
)
func init() {
dbType = conf.String("type")
user = conf.String("user")
password = conf.String("pass")
host = conf.String("host")
port = conf.String("port")
databaseName = conf.String("databaseName")
dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, password, host, port, databaseName)
// auto create database
createDb()
orm.RegisterDriver("mysql", orm.DRMySQL)
orm.RegisterDataBase("default", "mysql", dns)
}
func createDb() {
isCreate, _ := conf.Bool("isCreate")
// if database not created!
if !isCreate {
createDbSQL := fmt.Sprintf("CREATE DATABASE if not exists `%s` DEFAULT CHARACTER SET = 'utf8' DEFAULT COLLATE 'utf8_general_ci'", databaseName)
// connect mysql generate db object
db, err := sql.Open(dbType, dns)
defer db.Close()
if err != nil {
log.Fatal(err)
os.Exit(2)
}
if _, err := db.Exec(createDbSQL); err != nil {
log.Fatal(err)
os.Exit(2)
}
if err := conf.Set("isCreate", "1"); err != nil {
log.Fatal(err)
os.Exit(2)
}
}
}