Skip to content

Instantly share code, notes, and snippets.

@ulexxander
Created June 23, 2022 18:58
Show Gist options
  • Select an option

  • Save ulexxander/82e0700f9d10075d6b6b4a142688f9bf to your computer and use it in GitHub Desktop.

Select an option

Save ulexxander/82e0700f9d10075d6b6b4a142688f9bf to your computer and use it in GitHub Desktop.
Simple Go environment variables parsing
type env struct {
logLevel string
httpAddr string
natsURL string
mongoURI string
mongoDatabase string
stripeAPIKey string
stripeWebhookSigningSecret string
stripeOpenWeatherSubscriptionPriceID string
stripeRedirectsURL string
googleApplicationCredentials string
googlePlayAppPackageName string
googlePlayAppOpenWeatherSubscriptionID string
}
func parseEnv() (*env, error) {
const prefix = "SUBSVC_"
getenv := func(key string) string {
return os.Getenv(prefix + key)
}
optional := func(key, def string) string {
if val := getenv(key); val != "" {
return val
}
return def
}
var missingKeys []string
mandatory := func(key string) string {
if val := getenv(key); val != "" {
return val
}
missingKeys = append(missingKeys, key)
return ""
}
e := env{
logLevel: optional("LOG_LEVEL", logrus.TraceLevel.String()),
httpAddr: optional("HTTP_ADDR", ":80"),
natsURL: optional("NATS_URL", nats.DefaultURL),
mongoURI: optional("MONGO_URI", "mongodb://localhost:27017"),
mongoDatabase: optional("MONGO_DATABASE", "subscriptions-service"),
stripeAPIKey: mandatory("STRIPE_API_KEY"),
stripeWebhookSigningSecret: mandatory("STRIPE_WEBHOOK_SIGNING_SECRET"),
stripeOpenWeatherSubscriptionPriceID: mandatory("STRIPE_OPEN_WEATHER_SUBSCRIPTION_PRICE_ID"),
stripeRedirectsURL: optional("STRIPE_REDIRECTS_URL", "http://localhost:80/redirect/stripe"),
googleApplicationCredentials: optional("GOOGLE_APPLICATION_CREDENTIALS", "./google-service-account.json"),
googlePlayAppPackageName: mandatory("GOOGLE_PLAY_APP_PACKAGE_NAME"),
googlePlayAppOpenWeatherSubscriptionID: mandatory("GOOGLE_PLAY_APP_OPEN_WEATHER_SUBSCRIPTION_ID"),
}
if len(missingKeys) != 0 {
return nil, fmt.Errorf("variables not set or empty: %s", strings.Join(missingKeys, ", "))
}
return &e, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment