[golang notes] How to set environment variables for your project

Written byKalanKalan
💡

If you have any questions or feedback, pleasefill out this form

This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

Introduction

When developing a project, it's common to switch between different environments, which often necessitates setting various environment variables. However, hardcoding these values directly into the code can be cumbersome to modify each time. By dynamically passing environment variables, we can reduce unnecessary changes, resulting in cleaner code.

Flag

In Go, you can achieve similar functionality 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 this article that discusses using go build -ldflags to set variables at compile time.

While this approach does allow for not hardcoding values in the program, the variables still need to be defined beforehand.

Loading via YAML

To address the aforementioned issue, we can manage environment variables in a unified way using YAML (or any format you prefer). For example:

func LoadEnv(filename string) bool {
    file, err := ioutil.ReadFile(filename)
    if err != nil {
        // In production, we might set environment variables directly 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 store them uniformly using os.Setenv(k, v). This makes it easy to adjust variables in a local environment. Remember to ignore the configuration file in version control; otherwise, if it contains sensitive information and happens to be in a public repository, it could be exposed.

Conclusion

I've created a simple repo to handle this task. If you find it useful during development, feel free to optimize it further! XD

If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨

Buy me a coffee