Skip to content

Commit b410f8f

Browse files
committed
Setup config/config.go
1 parent 78b1419 commit b410f8f

2 files changed

Lines changed: 109 additions & 1 deletion

File tree

Gopkg.lock

Lines changed: 47 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

config/config.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package config
2+
3+
import (
4+
"fmt"
5+
"github.com/exlinc/golang-utils/envconfig"
6+
"github.com/sirupsen/logrus"
7+
)
8+
9+
// The envconfig struct tag is used to explicitly name the var, set defaults, and flag required values
10+
type Config struct {
11+
DBPath string `envconfig:"DB_PATH" required:"true"`
12+
Mode string `envconfig:"MODE" default:"production"`
13+
ListenAddress string `envconfig:"LISTEN_ADDRESS" default:"0.0.0.0"`
14+
ListenPort string `envconfig:"LISTEN_PORT" default:"3333"`
15+
AllowedOrigins []string `envconfig:"ALLOWED_ORIGINS" default:"*"`
16+
}
17+
18+
var conf *Config
19+
20+
const (
21+
DebugMode = "debug"
22+
ProductionMode = "production"
23+
)
24+
25+
// This function gets called automatically when the package is loaded
26+
func init() {
27+
conf = &Config{}
28+
// This prefix means our variables will be in the form of GDEMO_MODE (for example)
29+
err := envconfig.Process("GDEMO", conf)
30+
if err != nil {
31+
fmt.Println("Fatal error processing configuration")
32+
panic(err)
33+
}
34+
l := conf.GetLogger()
35+
36+
// Sanity check
37+
if !conf.IsDebugMode() && !conf.IsProductionMode() {
38+
l.Fatal("Invalid GDEMO_MODE variable, it must be either `debug` or `production`")
39+
}
40+
}
41+
42+
// Cfg returns the configuration - will panic if the config has not been loaded or is nil (which shouldn't happen as that's implicit in the package init)
43+
func Cfg() *Config {
44+
if conf == nil {
45+
panic("Config is nil")
46+
}
47+
return conf
48+
}
49+
50+
func (cfg *Config) GetLogger() *logrus.Logger {
51+
var l = logrus.New()
52+
l.Formatter = &logrus.JSONFormatter{}
53+
return l
54+
}
55+
56+
func (cfg *Config) IsDebugMode() bool {
57+
return cfg.Mode == DebugMode
58+
}
59+
60+
func (cfg *Config) IsProductionMode() bool {
61+
return cfg.Mode == ProductionMode
62+
}

0 commit comments

Comments
 (0)