0xBF
0xBF

0xBF

Go cheatsheet - Env

0xBF's photo
0xBF

Published on Apr 20, 2021

1 min read

Env

Functions to operate environment variables:

  • os.Getenv: get env variable by name, if not set, return empty string
  • os.LookupEnv: return (value, exists)
  • os.Setenv: set env variable value
  • os.Unsetenv: Unset env variable

Sample code:

package main

import (
    "fmt"
    "os"
)

func main() {
    dbConn := os.Getenv("DB_CONN")
    fmt.Println("DB Conn:", dbConn)

    dbConn, exists := os.LookupEnv("DB_CONN")
    if !exists {
        fmt.Println("Env is not set")
    } else {
        fmt.Println("DB Conn:", dbConn)
    }

    os.Setenv("DB_CONN", "mongodb://abc")
    dbConn = os.Getenv("DB_CONN")
    fmt.Println("DB Conn:", dbConn)    // mongodb://abc

    os.Unsetenv("DB_CONN")
}
 
Share this