-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
50 lines (42 loc) · 1003 Bytes
/
db.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
package main
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"net/url"
"os"
)
var db *gorm.DB
func initDb() {
conn, err := gorm.Open("postgres", getDbConfig())
if err != nil {
panic(err)
}
db = conn
initDbImport()
}
func getDbConfig() string {
var conf DbConfiguration = getConfigurationFromJson()
dsn := url.URL{
User: url.UserPassword(conf.Username, conf.Password),
Scheme: conf.Vendor,
Host: fmt.Sprintf("%s:%d", conf.Host, conf.Port),
RawQuery: (&url.Values{"sslmode": []string{"disable"}}).Encode(),
}
return dsn.String()
}
func initDbImport() {
db.Debug().AutoMigrate(&User{}, &Session{})
}
func getConfigurationFromJson() DbConfiguration {
file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := DbConfiguration{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("Unable to fetch configuration:", err)
}
return configuration
}