DEV Community

yanoandri
yanoandri

Posted on

Playing with Environment Variables in Golang

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}
Enter fullscreen mode Exit fullscreen mode

Then get and download specific dependencies from package github.com/joho/godotenv

go get github.com/joho/godotenv
go mod vendor
Enter fullscreen mode Exit fullscreen mode

Let's headed to the root directories of the project and created the file call .env with contents of

HELLO=from the other side
Enter fullscreen mode Exit fullscreen mode

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"))
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

this will have the same results

Results

Conclusion

Allright, this is it for a quick tutorial, Happy exploring!

Source

Oldest comments (0)