Last active
March 2, 2019 19:52
-
-
Save craicoverflow/88a3866f6c06d34d154c963404cdc044 to your computer and use it in GitHub Desktop.
Config file in Go which uses environment variables and falls back on a default value
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
package config | |
import ( | |
"os" | |
) | |
type GitHubConfig struct { | |
Username string | |
APIKey string | |
} | |
type Config struct { | |
GitHub GitHubConfig | |
} | |
// New returns a new Config struct | |
func New() *Config { | |
return &Config{ | |
GitHub: GitHubConfig{ | |
Username: getEnv("GITHUB_USERNAME", ""), | |
APIKey: getEnv("GITHUB_API_KEY", ""), | |
}, | |
} | |
} | |
// Simple helper function to read an environment or return a default value | |
func getEnv(key string, defaultVal string) string { | |
if value, exists := os.LookupEnv(key); exists { | |
return value | |
} | |
return defaultVal | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment