· 2 min read

How to Set Environment Variables for Your Golang Project

This article was auto-translated from Chinese. Some nuances may be lost in translation.

Introduction

When developing projects, we often need to switch between different environments, which is why we usually configure different environment variables. However, hardcoding them directly into the code makes modifications extremely tedious. Passing environment variables dynamically avoids a lot of unnecessary code changes and keeps the codebase cleaner.

flag

In Golang, you can typically use the flag package to achieve a similar effect. 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, using go build -ldflag to set variables at compile time.

While this does prevent hardcoding values into the code, the variables still need to be predefined.

Loading via YAML

To solve this problem, we can manage environment variables centrally using YAML (or any format you prefer). For example:

func LoadEnv(filename string) bool {
    file, err := ioutil.ReadFile(filename)
    if err != nil {
        // 在 production,我們可能會直接用 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, store them collectively using os.Setenv(k, v). This makes it very easy to adjust variables in a local environment. Just remember to add your configuration file to .gitignore—otherwise, if the variables contain sensitive data and your repository happens to be public, everything will be exposed.

Wrap-up

I created a fairly simple repo to accomplish this. If the need arises during development, I’ll continue optimizing it XD

Related Posts

Explore Other Topics