Skip to content

Instantly share code, notes, and snippets.

@daveteu
Last active June 23, 2022 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daveteu/038bdd45b2a335390ef1e5dfceed2497 to your computer and use it in GitHub Desktop.
Save daveteu/038bdd45b2a335390ef1e5dfceed2497 to your computer and use it in GitHub Desktop.
Golang - check env is loaded.
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
}
@daveteu
Copy link
Author

daveteu commented Jun 23, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment