Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

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.

Prev

Dynamically load modules via vuex and webpack dynamic import

Next

Japanese software industry common nouns conversion

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

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.