Environment variables are crucial for configuring Go applications, especially when dealing with sensitive information like database credentials and API keys. In this article, we'll explore a straightforward and effective solution for managing environment variables in Go using the godotenv package. We'll start with the installation guide for godotenv.
Installing godotenv
godotenv is a Go package that allows you to load environment variables from a .env file into your application. To get started, follow these steps to install it:
go get github.com/joho/godotenv
Setting up your Go Application
Before we dive into using godotenv, let's set up a simple Go application where we'll demonstrate its usage.
Project Structure
Here's an example project structure for your Go application:
myapp/
├── config/
│ ├── env.example
│ ├── local.env
│ └── profile.go
└── main.go
profile.go
package config
import (
"fmt"
"github.com/joho/godotenv"
"log"
"os"
)
type Profile string
const (
Local Profile = "local"
Test Profile = "test"
)
var Profiles = []Profile{Local, Test}
var ActiveProfile Profile
func CheckApplicationProfile() {
if len(os.Args) != 2 {
fmt.Println("Usage: ./your_app <profile>")
os.Exit(1)
}
profile := Profile(os.Args[1])
switch profile {
case Local, Test:
err := loadProfileEnvironments(profile)
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
ActiveProfile = profile
default:
fmt.Println("Invalid profile. Available profiles: ", Profiles)
os.Exit(1)
}
}
func loadProfileEnvironments(profile Profile) error {
envFile := fmt.Sprintf("config/%s.env", profile)
return godotenv.Load(envFile)
}
main.go
package main
import "myapp/config"
func main() {
config.CheckApplicationProfile()
// Your application logic goes here
}
Environment Variable Files
In the config directory, you'll find two environment variable files: env.example
and local.env
. These files contain sample environment variables that your application can use.
env.example
is a template for your environment variables, while local.env
contains specific values for the "local" profile.
env.example
# Example .env.example file
# Application port
PORT=3000
# Database URL
DATABASE_URL=mysql://username:password@localhost:3306/mydatabase
# Debug mode (true or false)
DEBUG=true
# JWT Secret key
JWT_SECRET=secret
Running Your Go Application with a Profile
To run your application with a profile, use the following command:
go run main.go <profile> # e.g. go run main.go local
Using Environment Variables in Your Go Application
Now that we've set up our Go application, let's see how we can use environment variables in it.
Accessing Environment Variables
dbHostString := os.Getenv("DATABASE_URL")
fmt.Println(dbHostString)
// Output: mysql://username:password@localhost:3306/mydatabase
Conclusion
In this article, we've explored a simple solution for managing environment variables in Go using the godotenv package. We've also seen how to set up a Go application with profiles and how to use environment variables in it. I hope you found this article helpful. If you have any questions or feedback, please leave a comment below.
For full code, GitHub.