This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
config.go
297 lines (278 loc) · 7.49 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package config
import (
"fmt"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
homedir "github.com/mitchellh/go-homedir"
"github.com/nuveo/log"
"github.com/prest/adapters"
"github.com/spf13/viper"
)
// TablesConf informations
type TablesConf struct {
Name string `mapstructure:"name"`
Permissions []string `mapstructure:"permissions"`
Fields []string `mapstructure:"fields"`
}
// AccessConf informations
type AccessConf struct {
Restrict bool
Tables []TablesConf
}
// Prest basic config
type Prest struct {
HTTPHost string // HTTPHost Declare which http address the PREST used
HTTPPort int // HTTPPort Declare which http port the PREST used
PGHost string
PGPort int
PGUser string
PGPass string
PGDatabase string
PGURL string
ContextPath string
SSLMode string
SSLCert string
SSLKey string
SSLRootCert string
PGMaxIdleConn int
PGMAxOpenConn int
PGConnTimeout int
JWTKey string
JWTAlgo string
MigrationsPath string
QueriesPath string
AccessConf AccessConf
CORSAllowOrigin []string
CORSAllowHeaders []string
Debug bool
Adapter adapters.Adapter
EnableDefaultJWT bool
EnableCache bool
HTTPSMode bool
HTTPSCert string
HTTPSKey string
}
var (
// PrestConf config variable
PrestConf *Prest
configFile string
defaultFile = "./prest.toml"
)
func viperCfg() {
configFile = getDefaultPrestConf(os.Getenv("PREST_CONF"))
dir, file := filepath.Split(configFile)
file = strings.TrimSuffix(file, filepath.Ext(file))
replacer := strings.NewReplacer(".", "_")
viper.SetEnvPrefix("PREST")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(replacer)
viper.AddConfigPath(dir)
viper.SetConfigName(file)
viper.SetConfigType("toml")
viper.SetDefault("http.host", "0.0.0.0")
viper.SetDefault("http.port", 3000)
viper.SetDefault("pg.host", "127.0.0.1")
viper.SetDefault("pg.port", 5432)
viper.SetDefault("ssl.mode", "disable")
viper.SetDefault("pg.maxidleconn", 10)
viper.SetDefault("pg.maxopenconn", 10)
viper.SetDefault("pg.conntimeout", 10)
viper.SetDefault("debug", false)
viper.SetDefault("jwt.default", true)
viper.SetDefault("jwt.algo", "HS256")
viper.SetDefault("cors.allowheaders", []string{"*"})
viper.SetDefault("cache.enable", true)
viper.SetDefault("context", "/")
viper.SetDefault("https.mode", false)
viper.SetDefault("https.cert", "/etc/certs/cert.crt")
viper.SetDefault("https.key", "/etc/certs/cert.key")
hDir, err := homedir.Dir()
if err != nil {
log.Fatal(err)
}
viper.SetDefault("queries.location", filepath.Join(hDir, "queries"))
}
func getDefaultPrestConf(prestConf string) (cfg string) {
cfg = prestConf
if prestConf == "" {
cfg = defaultFile
_, err := os.Stat(cfg)
if err != nil {
cfg = ""
}
}
return
}
// Parse pREST config
func Parse(cfg *Prest) (err error) {
err = viper.ReadInConfig()
if err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
if configFile != "" {
log.Fatal(fmt.Sprintf("File %s not found. Aborting.\n", configFile))
}
default:
return
}
}
cfg.HTTPHost = viper.GetString("http.host")
cfg.HTTPPort = viper.GetInt("http.port")
err = httpFromEnv(cfg)
if err != nil {
return
}
cfg.PGURL = viper.GetString("pg.url")
cfg.PGHost = viper.GetString("pg.host")
cfg.PGPort = viper.GetInt("pg.port")
cfg.PGUser = viper.GetString("pg.user")
cfg.PGPass = viper.GetString("pg.pass")
cfg.PGDatabase = viper.GetString("pg.database")
err = postgresFromEnv(cfg)
if err != nil {
return
}
cfg.SSLMode = viper.GetString("ssl.mode")
cfg.SSLCert = viper.GetString("ssl.cert")
cfg.SSLKey = viper.GetString("ssl.key")
cfg.SSLRootCert = viper.GetString("ssl.rootcert")
cfg.PGMaxIdleConn = viper.GetInt("pg.maxidleconn")
cfg.PGMAxOpenConn = viper.GetInt("pg.maxopenconn")
cfg.PGConnTimeout = viper.GetInt("pg.conntimeout")
cfg.JWTKey = viper.GetString("jwt.key")
cfg.JWTAlgo = viper.GetString("jwt.algo")
jwtFromEnv(cfg)
cfg.MigrationsPath = viper.GetString("migrations")
cfg.AccessConf.Restrict = viper.GetBool("access.restrict")
cfg.QueriesPath = viper.GetString("queries.location")
cfg.CORSAllowOrigin = viper.GetStringSlice("cors.alloworigin")
cfg.CORSAllowHeaders = viper.GetStringSlice("cors.allowheaders")
cfg.Debug = viper.GetBool("debug")
cfg.EnableDefaultJWT = viper.GetBool("jwt.default")
cfg.EnableCache = viper.GetBool("cache.enable")
cfg.ContextPath = viper.GetString("context")
cfg.HTTPSMode = viper.GetBool("https.mode")
cfg.HTTPSCert = viper.GetString("https.cert")
cfg.HTTPSKey = viper.GetString("https.key")
var t []TablesConf
err = viper.UnmarshalKey("access.tables", &t)
if err != nil {
return
}
cfg.AccessConf.Tables = t
return
}
// Load configuration
func Load() {
viperCfg()
PrestConf = &Prest{}
err := Parse(PrestConf)
if err != nil {
panic(err)
}
if _, err = os.Stat(PrestConf.QueriesPath); os.IsNotExist(err) {
if err = os.MkdirAll(PrestConf.QueriesPath, 0700); os.IsNotExist(err) {
log.Errorf("Queries directory %s is not created", PrestConf.QueriesPath)
}
}
}
func postgresFromEnv(cfg *Prest) (err error) {
// rewrite all pg config
if pgURL, ok := os.LookupEnv("PREST_PG_URL"); ok {
cfg.PGURL = pgURL
return parseDatabaseURL(cfg)
}
// rewrite all pg config
if pgURL, ok := os.LookupEnv("DATABASE_URL"); ok {
// cloud factor support: https://devcenter.heroku.com/changelog-items/438
cfg.PGURL = pgURL
return parseDatabaseURL(cfg)
}
// rewrite pg host
if pgHost, ok := os.LookupEnv("PREST_PG_HOST"); ok {
cfg.PGHost = pgHost
}
// rewrite pg user
if pgUser, ok := os.LookupEnv("PREST_PG_USER"); ok {
cfg.PGUser = pgUser
}
// rewrite pg pass
if pgPass, ok := os.LookupEnv("PREST_PG_PASS"); ok {
cfg.PGPass = pgPass
}
// rewrite pg database
if pgDatabase, ok := os.LookupEnv("PREST_PG_DATABASE"); ok {
cfg.PGDatabase = pgDatabase
}
// rewrite pg port
if pgPort, ok := os.LookupEnv("PREST_PG_PORT"); ok {
PGPort, err := strconv.Atoi(pgPort)
if err != nil {
return err
}
cfg.PGPort = PGPort
}
return
}
func jwtFromEnv(cfg *Prest) {
// rewrite jwt key
if jwtKey, ok := os.LookupEnv("PREST_JWT_KEY"); ok {
cfg.JWTKey = jwtKey
}
// rewrite jwt algo
if jwtAlgo, ok := os.LookupEnv("PREST_JWT_ALGO"); ok {
cfg.JWTAlgo = jwtAlgo
}
}
func parseDatabaseURL(cfg *Prest) (err error) {
if cfg.PGURL == "" {
return
}
// Parser PG URL, get database connection via string URL
u, errPerse := url.Parse(cfg.PGURL)
if errPerse != nil {
err = errPerse
return
}
cfg.PGHost = u.Hostname()
if u.Port() != "" {
pgPort, PortErr := strconv.Atoi(u.Port())
if PortErr != nil {
return PortErr
}
cfg.PGPort = pgPort
}
cfg.PGUser = u.User.Username()
pgPass, pgPassExist := u.User.Password()
if pgPassExist {
cfg.PGPass = pgPass
}
cfg.PGDatabase = strings.Replace(u.Path, "/", "", -1)
if u.Query().Get("sslmode") != "" {
cfg.SSLMode = u.Query().Get("sslmode")
}
return
}
func httpFromEnv(cfg *Prest) (err error) {
if httpHost, ok := os.LookupEnv("PREST_HTTP_HOST"); ok {
cfg.HTTPHost = httpHost
}
if httpPort, ok := os.LookupEnv("PREST_HTTP_PORT"); ok {
HTTPPort, err := strconv.Atoi(httpPort)
if err != nil {
return err
}
cfg.HTTPPort = HTTPPort
} else if port, ok := os.LookupEnv("PORT"); ok {
// cloud factor support: https://help.heroku.com/PPBPA231/how-do-i-use-the-port-environment-variable-in-container-based-apps
HTTPPort, err := strconv.Atoi(port)
if err != nil {
return err
}
cfg.HTTPPort = HTTPPort
}
return
}