Skip to content

Instantly share code, notes, and snippets.

@craicoverflow
Last active March 2, 2019 19:52
Show Gist options
  • Save craicoverflow/88a3866f6c06d34d154c963404cdc044 to your computer and use it in GitHub Desktop.
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
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