'github.com/vrischmann/envconfig'
allows you to read the configuraition from environment variables.
Step 1: Create a structure that can hold all
the configuration values.
var conf struct
{
Admin struct {
UserName string
`envconfig:"default=Krishna"`
PassWord string
`envconfig:"default=admin123"`
}
BaseURL string
`envconfig:"default=abc.com"`
}
As you see
above struct, It is holding Admin details and BaseURL to connect to. If the values are not presented in
environment, it can take the default values provided in the struct.
Whenever
you want to get the configurations from conf object, it checks for below keys
in the environment.
BaseURL or
baseurl
ADMIN_USERNAME,
or admin_username
ADMIN_PASSWORD,
or admin_password
Step 2: Set the Environment variables.
os.Setenv("ADMIN_USERNAME",
"admin")
os.Setenv("ADMIN_PASSWORD",
"password123")
if err :=
envconfig.Init(&conf); err != nil {
fmt.Printf("err=%s\n", err)
}
Step 3: Now whenever you access the
configuration values, you can get the values that are set in os environment, if
no value set, then you will get the default value.
fmt.Println("User
Name : ", conf.Admin.UserName)
fmt.Println("Password
: ", conf.Admin.Password)
fmt.Println("Base
URL", conf.BaseURL)
App.go
package main import ( "fmt" "os" "github.com/vrischmann/envconfig" ) var conf struct { Admin struct { UserName string `envconfig:"default=Krishna"` Password string `envconfig:"default=admin123"` } BaseURL string `envconfig:"default=abc.com"` } func main() { os.Setenv("ADMIN_USERNAME", "admin") os.Setenv("ADMIN_PASSWORD", "password123") if err := envconfig.Init(&conf); err != nil { fmt.Printf("err=%s\n", err) } fmt.Println("User Name : ", conf.Admin.UserName) fmt.Println("Password : ", conf.Admin.Password) fmt.Println("Base URL", conf.BaseURL) }
Output
User Name
: admin
Password
: password123
Base URL
abc.com
No comments:
Post a Comment