Last active
June 23, 2022 15:05
-
-
Save daveteu/038bdd45b2a335390ef1e5dfceed2497 to your computer and use it in GitHub Desktop.
Golang - check env is loaded.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"fmt" | |
"reflect" | |
log "github.com/sirupsen/logrus" | |
"github.com/spf13/viper" | |
) | |
type Config struct { | |
MongoHost string | |
MongoPort int | |
MongoUserName string | |
MongoPassword string | |
AppPort int | |
} | |
var AppConfig Config | |
func Load() error { | |
viper.AutomaticEnv() | |
AppConfig = Config{ | |
MongoHost: viper.GetString("MongoHost"), | |
MongoPort: viper.GetInt("MongoPort"), | |
MongoUserName: viper.GetString("MongoUserName"), | |
MongoPassword: viper.GetString("MongoPassword"), | |
AppPort: viper.GetString("AppPort"), | |
} | |
v := reflect.ValueOf(AppConfig) | |
typeOfV := v.Type() | |
for i := 0; i < v.NumField(); i++ { | |
if fmt.Sprintf("%v", v.Field(i).Interface()) == "" { | |
log.Warn(fmt.Sprintf("Value of environment var %s is empty.", typeOfV.Field(i).Name)) | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fields in struct has to be exported (big caps) else warning will be thrown.
This is also a demonstration on how we can loop through structs to get key/value pair.