File tree Expand file tree Collapse file tree 6 files changed +668
-0
lines changed Expand file tree Collapse file tree 6 files changed +668
-0
lines changed Original file line number Diff line number Diff line change 1+ app_port : 8080
2+ app_name : " brew_machine"
3+ log_level : " info"
Original file line number Diff line number Diff line change 1+ app_port : 8080
2+ app_name : " brew_machine"
3+ log_level : " info"
Original file line number Diff line number Diff line change 1+ package config
2+
3+ import (
4+ "github.com/spf13/viper"
5+ )
6+
7+ type Config struct {
8+ appPort int
9+ appName string
10+ logLevel string
11+ }
12+
13+ var appConfiguration * Config
14+
15+ func LoadTestConfig () {
16+ load ("application_test" )
17+ }
18+
19+ func Load () {
20+ load ("application" )
21+ }
22+
23+ func load (configFileName string ) {
24+ viper .AutomaticEnv ()
25+ viper .SetConfigName (configFileName )
26+ viper .SetConfigType ("yaml" )
27+ viper .AddConfigPath ("./" )
28+ viper .AddConfigPath ("../" )
29+ viper .AddConfigPath ("../../" )
30+ viper .ReadInConfig ()
31+
32+ appConfiguration = & Config {
33+ appPort : getIntOrPanic ("app_port" ),
34+ appName : getStringOrPanic ("app_name" ),
35+ logLevel : getStringOrPanic ("log_level" ),
36+ }
37+
38+ return
39+ }
40+
41+ func AppPort () int {
42+ return appConfiguration .appPort
43+ }
44+
45+ func AppName () string {
46+ return appConfiguration .appName
47+ }
48+
49+ func LogLevel () string {
50+ return appConfiguration .logLevel
51+ }
Original file line number Diff line number Diff line change 1+ package config
2+
3+ import (
4+ "errors"
5+ "fmt"
6+ "os"
7+ "strconv"
8+
9+ "github.com/spf13/viper"
10+ )
11+
12+ func getIntOrPanic (key string ) int {
13+ intValue , err := strconv .Atoi (getConfigStringValue (key ))
14+ if err != nil {
15+ panicForkey (key , err )
16+ }
17+ return intValue
18+ }
19+
20+ func getBoolOrPanic (key string ) bool {
21+ boolValue , err := strconv .ParseBool (getConfigStringValue (key ))
22+ if err != nil {
23+ panicForkey (key , err )
24+ }
25+ return boolValue
26+ }
27+
28+ func getStringOrPanic (key string ) string {
29+ value := getConfigStringValue (key )
30+ if value == "" {
31+ panicForkey (key , errors .New ("config is not set" ))
32+ }
33+ return value
34+ }
35+
36+ func getConfigStringValue (key string ) string {
37+ if ! viper .IsSet (key ) && os .Getenv (key ) == "" {
38+ fmt .Printf ("config %s is not set\n " , key )
39+ }
40+ value := os .Getenv (key )
41+ if value == "" {
42+ value = viper .GetString (key )
43+ }
44+ return value
45+ }
46+
47+ func panicForkey (key string , err error ) {
48+ panic (fmt .Sprintf ("Error %v occured while reading config %s" , err .Error (), key ))
49+ }
Original file line number Diff line number Diff line change 11module nipun.io/brew_machine
22
33go 1.16
4+
5+ require (
6+ github.com/spf13/viper v1.8.1
7+ )
You can’t perform that action at this time.
0 commit comments