Rabi Siddique
137 words
1 minutes
Loading and Using Environment Variables in GO
2024-02-07

The os package in Go provides functionality to interact with the host operating system. This includes setting and getting environment variables as key-value pairs. Here’s an example:

import ("os", "fmt")

err := os.Setenv("KEY","VALUE")

if err != nil {
    return
}

value := os.Getenv("KEY")

fmt.Println(value)

A better, more secure, and adaptable way is to use a .env file, especially if you have multiple environments like Staging, QA, and Production. Here are the steps:

1. Download dotenv package#

go get github.com/joho/godotenv

2. Load the values in your application:#

import (
    "log"
    "github.com/joho/godotenv"
    "fmt"
    "os"
)

// init is invoked before main()
func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
        log.Print("No .env file found")
    }
}

3. Start using the variables in your code:#

os.Getenv("WEATHER_API_KEY")

Useful Links#

Loading and Using Environment Variables in GO
https://rabisiddique.com/posts/go-env-variables/
Author
Rabi Siddique
Published at
2024-02-07