genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0

[TASK] add database connection

This commit is contained in:
Martin Geno 2017-03-30 16:09:44 +02:00
parent 2921580e11
commit 75a378a0cd
5 changed files with 75 additions and 2 deletions

View File

@ -10,6 +10,7 @@ import (
goji "goji.io"
web "github.com/genofire/hs_master-kss-monolith/http"
"github.com/genofire/hs_master-kss-monolith/lib/database"
"github.com/genofire/hs_master-kss-monolith/lib/log"
"github.com/genofire/hs_master-kss-monolith/models"
)
@ -28,6 +29,11 @@ func main() {
log.Log.Info("Starting rezension monolith")
err := database.Open(config.Database)
if err != nil{
log.Log.Panic(err)
}
// Startwebsrver
router := goji.NewMux()
web.BindAPI(router)
@ -44,6 +50,7 @@ func main() {
// Stop services
srv.Close()
database.Close()
log.Log.Info("received", sig)
}

View File

@ -1 +1,7 @@
webserver_bind = ":8080"
[database]
type = "sqlite"
connection = "file::memory:?mode=memory&cache=shared"
# For Master-Slave cluster
# read_connection = ""

49
lib/database/main.go Normal file
View File

@ -0,0 +1,49 @@
package database
import (
"errors"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var (
Write *gorm.Database
Read *gorm.Database
config *Config
models []interface{}
)
type Config struct {
Type string
Connection string
ReadConnection string
}
func Open(c Config) (err errors.Error) {
config = &c
Write, err = gorm.Open(config.Type, config.Connection)
if err != nil {
return
}
if len(config.ReadConnection) > 0 {
Read, err = gorm.Open(config.Type, config.ReadConnection)
} else {
Read = Write
}
Write.AutoMigrate(models...)
return
}
func Close() {
Write.Close()
if len(config.ReadConnection) > 0 {
Read.Close()
}
}
func AddModel(m interface{}) {
models = append(models, m)
}

View File

@ -0,0 +1,3 @@
package database

View File

@ -4,11 +4,19 @@ import (
"io/ioutil"
"github.com/influxdata/toml"
"github.com/genofire/hs_master-kss-monolith/lib/log"
"github.com/genofire/hs_master-kss-monolith/lib/database"
)
//Config the config File of this daemon
type Config struct {
WebserverBind string
Database struct {
Type string
Connection string
ReadConnection string
}
}
// ReadConfigFile reads a config model from path of a yml file
@ -16,11 +24,11 @@ func ReadConfigFile(path string) *Config {
config := &Config{}
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
log.Log.Panic(err)
}
if err := toml.Unmarshal(file, config); err != nil {
panic(err)
log.Log.Panic(err)
}
return config