Introduction
Hi, in this session we will learn how to read variable keys from .env
file into our code, or we use to call it by handling environment variables in Golang.
Hands On
This will be a very quick tutorial, so let's just start it by initializing the project modules.
go mod init {your package name}
Then get and download specific dependencies from package github.com/joho/godotenv
go get github.com/joho/godotenv
go mod vendor
Let's headed to the root directories of the project and created the file call .env
with contents of
HELLO=from the other side
and run our main script in main.go
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func init() {
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
}
func main() {
fmt.Printf("%s", os.Getenv("HELLO"))
}
Or if we do not want to mix things up with os.GetEnv
, we can just also use it like this
package main
import (
"fmt"
"log"
"github.com/joho/godotenv"
)
func main() {
var envs map[string]string
envs, err := godotenv.Read(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
hello := envs["HELLO"]
fmt.Printf("%s", hello)
}
this will have the same results
Conclusion
Allright, this is it for a quick tutorial, Happy exploring!
Top comments (0)