Loading Environment Variables
With the package from "github.com/joho/godotenv" it is very easy to load Environment Variables from a .env file.
E.g. we have a .env file with an API key:
API=123-456-XXX-789We want to load it to our Go Program and can do it easily:
func main() {
// Load will read your env file(s) and load them into ENV for this process.
// If you call Load without any args it will default to loading .env in the current path.
err := godotenv.Load()
if err != nil {
// Fatalf is equivalent to [Printf] followed by a call to os.Exit(1)
log.Fatalf("err loading: %v", err)
}
// Get the value of the env variable by passing its variable name
api_key := os.Getenv("API")
}This way, our API Key is loaded from the .env file and stored inside our api_key variable.
Last updated