How to Set Environment Variables for Your Golang Project
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
- When a Measure Becomes a Target: From the Window Tax to Pull Request Counts I once wrote a script to tally how many PRs I contributed in a quarter, how many reviews I left, and how many tickets I closed, hoping to use numbers to prove my output to my manager. My manager simply remarked that performance isn't just about output. Years later, I finally understood—when a measure becomes a target, it ceases to be a good measure. From the British window tax and the Hanoi rat bounty to evaluating developers by PR counts today, the underlying mechanism is exactly the same.
- Using Cloudflare Images for Image Storage and Transformation Putting an image on a webpage is the simplest task in frontend development. But doing it properly—including resizing, generating multiple formats, and withstanding heavy traffic—is actually an entire end-to-end solution. Eventually, I offloaded everything to Cloudflare Images, keeping only a single original image.
- Stop Using AWS Access Keys Access Keys are an easily overlooked security risk in AWS. By pairing OIDC with IAM Roles, GitHub Actions can securely operate AWS resources without storing any secrets.
- Database Primary Keys: AUTO_INCREMENT, UUID, and UUIDv7 Backend developers often face the choice of primary keys: should you use auto-increment or UUID? What about collisions? How does UUIDv7 compare to created_at + index in performance? Here are the design decisions and benchmark results from testing 20 million rows.