-
-
Save avary/cf9aa36280ed8f10349b83ffda0a6e4b to your computer and use it in GitHub Desktop.
Load TOML config and pick environment from a environmental variable in Go
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
[dev] | |
url = "http://dev.example.com" | |
username = "dev.account" | |
password = "devdev" | |
[test] | |
url = "http://test.example.com" | |
username = "test.account" | |
password = "testtest" | |
[prod] | |
url = "http://prod.example.com" | |
username = "prod.account" | |
password = "prodprod" |
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 main | |
import ( | |
"fmt" | |
"github.com/naoina/toml" | |
"io/ioutil" | |
"os" | |
"reflect" | |
) | |
type AppConfig struct { | |
Url string | |
Username string | |
Password string | |
} | |
type Config struct { | |
Dev AppConfig | |
Test AppConfig | |
Prod AppConfig | |
} | |
const CONFIG = "config.toml" | |
func loadAppConfig(config Config, env string) AppConfig { | |
r := reflect.ValueOf(config) | |
return reflect.Indirect(r).FieldByName(env).Interface().(AppConfig) | |
} | |
func main() { | |
fmt.Printf("Loading config file: %s\n", CONFIG) | |
configData, err := ioutil.ReadFile(CONFIG) | |
if err != nil { | |
panic(err) | |
} | |
var config Config | |
err = toml.Unmarshal(configData, &config) | |
if err != nil { | |
panic(err) | |
} | |
env := os.Getenv("APP_ENV") | |
if env == "" { | |
env = "Dev" | |
} | |
appConfig := loadAppConfig(config, env) | |
fmt.Printf("%#v\n", appConfig) | |
fmt.Printf("Environment set to %s\n", env) | |
} | |
// go build -o app | |
// ./app | |
// APP_ENV=Test ./app | |
// APP_ENV=Prod ./app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment