Preface
When developing a project, it is often necessary to switch between different environments. Therefore, we usually set different environment variables. However, hardcoding them in the program can be quite cumbersome to modify. If we can pass in environment variables dynamically, it can reduce unnecessary modifications and make the code cleaner.
flag
In Go, we can achieve a similar effect using the flag package. For example:
var env string
var accessToken string
func main() {
flag.StringVar(&env, 'ENV', 'development', 'your current env')
flag.StringVar(&accessToken, 'ACCESS_TOKEN', 'xxx-oo-ooo', 'your API access token')
flag.Parse()
// start your application
}
Alternatively, you can refer to the approach mentioned in this article to set variables during compile time using go build -ldflag
.
Although this approach avoids hardcoding values in the program, the variables still need to be defined in advance.
Loading via YAML
To solve the above problem, we can use YAML (or your preferred format) to manage environment variables uniformly. For example:
func LoadEnv(filename string) bool {
file, err := ioutil.ReadFile(filename)
if err != nil {
// In production, we may directly set environment variables via the console.
return false
}
var config := make(map[string]string)
yaml.Unmarshal(file, &config)
for k, v := range config {
os.Setenv(k, v)
}
}
After loading the variables from the YAML file, we use os.Setenv(k, v)
to store them uniformly. This makes it easy to adjust the variables in the local environment. Remember to add the configuration file to the ignore list, as sensitive information may be exposed if the variables are stored in a public repository.
Afterword
I created a simple repository to accomplish this. If you really need it in your development, feel free to continue optimizing it XD.