-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
122 lines (104 loc) · 2.34 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package config
import (
"errors"
"log"
"os"
"time"
"github.com/spf13/viper"
)
type Config struct {
Server ServerConfig
Postgres PostgresConfig
Password PasswordConfig
Logger LoggerConfig
JWT JWTConfig
API APIConfig
}
type ServerConfig struct {
InternalPort string
ExternalPort string
RunMode string
}
type LoggerConfig struct {
FilePath string
Encoding string
Level string
Logger string
}
type PostgresConfig struct {
Host string
Port string
User string
Password string
DbName string
SSLMode string
MaxIdleConns int
MaxOpenConns int
ConnMaxLifetime time.Duration
}
type PasswordConfig struct {
IncludeChars bool
IncludeDigits bool
MinLength int
MaxLength int
IncludeUppercase bool
IncludeLowercase bool
}
type JWTConfig struct {
AccessTokenExpireDuration time.Duration
RefreshTokenExpireDuration time.Duration
Secret string
RefreshSecret string
}
type APIConfig struct {
BaseUrl string
Token string
}
func GetConfig() *Config {
cfgPath := getConfigPath(os.Getenv("APP_ENV"))
v, err := LoadConfig(cfgPath, "yml")
if err != nil {
log.Fatalf("Error in load config %v", err)
}
cfg, err := ParseConfig(v)
envPort := os.Getenv("PORT")
if envPort != ""{
cfg.Server.ExternalPort = envPort
log.Printf("Set external port from environment -> %s", cfg.Server.ExternalPort)
}else{
cfg.Server.ExternalPort = cfg.Server.InternalPort
log.Printf("Set external port from environment -> %s", cfg.Server.ExternalPort)
}
if err != nil {
log.Fatalf("Error in parse config %v", err)
}
return cfg
}
func ParseConfig(v *viper.Viper) (*Config, error) {
var cfg Config
err := v.Unmarshal(&cfg)
if err != nil {
log.Printf("Unable to parse config: %v", err)
return nil, err
}
return &cfg, nil
}
func LoadConfig(filename string, fileType string) (*viper.Viper, error) {
v := viper.New()
v.SetConfigType(fileType)
v.SetConfigName(filename)
v.AddConfigPath(".")
v.AutomaticEnv()
err := v.ReadInConfig()
if err != nil {
log.Printf("Unable to read config: %v", err)
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
return nil, errors.New("config file not found")
}
return nil, err
}
return v, nil
}
func getConfigPath(env string) string {
return "../config/config-development"
}