Kalan's Blog

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

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

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

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