How to use dotenv in Golang
2 min readMay 10, 2023
Hello, today I will show you how to use dotenv (also known as .env) in Golang!
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. The dotenv package is a great way to keep passwords, API keys, and other sensitive data out of your code. It allows you to create environment variables in a . env file instead of putting them in your code.
Step 1: Init and install packages.
Init our project:
go mod init dotenv
Install package:
go get github.com/joho/godotenv
Step 2: .env file
Write some values to the .env file:
GREETING="Hello World"
Step 3: Find .env file:
You must write the right .env file directory relative to the distance from main.go:
func main(){
// Find .env file
err := godotenv.Load(".env")
if err != nil{
log.Fatalf("Error loading .env file: %s", err)
}
}
Step 4: Getting and using a value from .env
With a simple method, we can get any value from the .env:
func main(){
// Find .env file
err := godotenv.Load(".env")
if err != nil{
log.Fatalf("Error loading .env file: %s", err)
}
// Getting and using a value from .env
greeting := os.Getenv("GREETING")
fmt.Println(greeting)
}
The full code
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func main(){
// Find .env file
err := godotenv.Load(".env")
if err != nil{
log.Fatalf("Error loading .env file: %s", err)
}
// Getting and using a value from .env
greeting := os.Getenv("GREETING")
fmt.Println(greeting)
}
Thank you for the read this article!
You can buy me a coffee!