logo
  • 現在做什麼
  • 關於我

Kalan

文章分類

  • 前端
  • 開發筆記
  • 雜談
  • 年度回顧

快速連結

  • 現在做什麼
  • 關於我
  • 聯絡我
  • 職涯思考🔗

關注我

在福岡生活的開發者,分享軟體開發與日本生活的點點滴滴。

© 2025 Kalan Made with ❤️. All rights reserved.

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

Written byKalanKalanSep 3, 2018
Home/Dev Note
💡

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

Japanese原文

Table of Contents

  1. Introduction
  2. Flag
  3. Loading via YAML
  4. Conclusion

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

← Dynamically load modules via vuex and webpack dynamic importJapanese software industry common nouns conversion →

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

☕Buy me a coffee

Table of Contents

  1. Introduction
  2. Flag
  3. Loading via YAML
  4. Conclusion