[golang notes] How to set environment variables for your project
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
Related Posts
- When Measurement Becomes the Goal: From Window Tax to PR Counts I once wrote a small tool to count how many PRs I had contributed in a quarter, how many reviews I had left, and how many tickets I had closed, hoping to use the numbers to prove my output to my manager. My manager simply said performance is not judged by output alone. Only years later did I understand—when measurement becomes the goal, it is no longer a good measure. From Britain’s window tax and the Hanoi rat bounty to evaluating developers by PR count today, the mechanism is exactly the same.
- Using Cloudflare Images for Image Storage and Transformation Putting an image on a web page is the easiest thing in frontend. But doing it properly — resizing, generating every format, holding up under traffic — turns into a whole solution of its own. I ended up handing all of it to Cloudflare Images and keeping just one original.
- Stop Using Access Keys Already Access Keys are an easily overlooked security risk on AWS. Use OIDC with IAM Roles so GitHub Actions can securely access AWS resources without any secrets.
- Database Primary Keys: AUTO_INCREMENT, UUID, and UUIDv7 Backend developers often have to decide on a primary key: auto increment or UUID? What about collisions? How much faster is UUIDv7 compared with created_at + index? After benchmarking 20 million rows and looking at the design trade-offs, this post gives you the answer.