Skip to content

Instantly share code, notes, and snippets.

@ghiden
Last active August 17, 2023 07:59
Show Gist options
  • Save ghiden/0ff00fe355a24e790512 to your computer and use it in GitHub Desktop.
Save ghiden/0ff00fe355a24e790512 to your computer and use it in GitHub Desktop.
Load TOML config and pick environment from a environmental variable in Go
[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"
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