Welcome To Golang By Example

Set or Unset or Get Environment Variables in Golang

Overview

os package provides a couple of utility methods related to playing around env variables in Go.

Setting an env value

func Setenv(key, value string) error

Get an env value

The value returned by the Getenv() function will be empty if that env variable is not present. To differentiate between an unset and empty env variable use LookupEnv() function which an additional boolean indicating if the env variable was present or not.

func Getenv(key string) string

Unset an env value

func Unsetenv(key string) error 

Lookup for an env variable

As evident from the below signature, LookupEnv returns additional boolean.

func LookupEnv(key string) (string, bool)

Code:

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    //Set env a to b
    err := os.Setenv("a", "b")
    if err != nil {
        log.Fatal(err)
    }
   
    //Get env a
    val := os.Getenv("a")
    fmt.Println(val)
    
    //Unset a
    err = os.Unsetenv("a")
    if err != nil {
        log.Fatal(err)
    }
    
    val, present := os.LookupEnv("a")
    fmt.Printf("a env variable present: %t\n", present)
}

Output:

b
a env variable present: false