This repository was archived by the owner on Jan 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
68 lines (60 loc) · 1.76 KB
/
config.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
package main
import (
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"github.com/spf13/viper"
"github.com/zevst/gomig/driver"
"github.com/zevst/gomig/errors"
"github.com/zevst/zlog"
"os"
"strings"
)
var (
ErrDatabaseNotFound = errors.New("Database not found")
ErrDatabaseNotConfigured = errors.New("Database not configured")
ErrDialectNotFound = errors.New("Database dialect not found. You can add your own dialect using gorm.RegisterDialect")
ErrFilesNotFound = errors.New("Files not found")
ErrUndefinedMigrationType = errors.New("Undefined type of migration file")
)
func init() {
_ = godotenv.Load()
viper.SetEnvPrefix("GOMIG")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
viper.SetConfigType(getEnv("GOMIG_CONFIG_TYPE", "yaml"))
viper.AddConfigPath(getEnv("GOMIG_CONFIG_PATH", "config"))
viper.SetConfigName(getEnv("GOMIG_CONFIG_NAME", "default"))
}
type database struct {
Dialect string `mapstructure:"dialect"`
Dsn string `mapstructure:"dsn"`
TableOptions []string `mapstructure:"table_options"`
}
func (d *database) Connect() (conn *gorm.DB, err error) {
switch d.Dialect {
case driver.MySQL:
conn, err = driver.MySQLConn(d.Dsn)
case driver.PgSQL:
conn, err = driver.PgSQLConn(d.Dsn)
default:
return nil, ErrDialectNotFound
}
if err != nil {
return nil, err
}
if len(d.TableOptions) > 0 {
conn.Set("gorm:table_options", strings.Join(d.TableOptions, " "))
}
return conn, conn.AutoMigrate(&Entity{}).Error
}
type Config struct {
Databases map[string]*database `mapstructure:"db"`
Loggers zlog.MultiLogger `mapstructure:"loggers"`
}
var config *Config
func getEnv(key, def string) string {
if env := os.Getenv(key); env != "" {
return env
}
return def
}