This repository has been archived by the owner on Jan 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
74 lines (58 loc) · 1.62 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
69
70
71
72
73
74
package server
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
HttpAddr string
dbProtocol string
dbAddress string
dbName string
dbUsername string
dbPassword string
JwtPrivateKey string
JwtPublicKey string
TokenExpiry int
}
func NewConfig(configPath string) *Config {
viper.SetConfigName("config")
viper.AddConfigPath(configPath)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
config := &Config{
HttpAddr: viper.GetString("httpAddr"),
dbProtocol: viper.GetString("database.protocol"),
dbAddress: viper.GetString("database.address"),
dbName: viper.GetString("database.name"),
dbUsername: viper.GetString("database.username"),
dbPassword: viper.GetString("database.password"),
JwtPrivateKey: viper.GetString("jwt.privateKey"),
JwtPublicKey: viper.GetString("jwt.publicKey"),
TokenExpiry: viper.GetInt("jwt.tokenExpiry"),
}
if config.dbName == "" {
panic("Fatal error: dbName not specified")
}
return config
}
func (config *Config) GetDataSourceName() string {
// https://github.com/go-sql-driver/mysql#dsn-data-source-name
// [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
dsn := "/" + config.dbName + "?parseTime=true"
if config.dbAddress != "" {
dsn = config.dbProtocol + "(" + config.dbAddress + ")" + dsn
}
var dsnUser string
if config.dbUsername != "" {
dsnUser = config.dbUsername
if config.dbPassword != "" {
dsnUser += ":" + config.dbPassword
}
}
if dsnUser != "" {
dsn = dsnUser + "@" + dsn
}
return dsn
}