Created
June 23, 2022 18:58
-
-
Save ulexxander/82e0700f9d10075d6b6b4a142688f9bf to your computer and use it in GitHub Desktop.
Simple Go environment variables parsing
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
| 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