Get and Set Environment Variables

Environment variables are a useful way to work with sensitive information (think passwords) which your code needs to work with, but don’t need to be checked into your code base. With Go, you can both get and set these details using the os library.

package main

import (
    "fmt"
    "os"
)

func main() {
    // Outputs your 'visual' env var (in my case 'vim' (set in ~/.bashrc))
    fmt.Println(os.Getenv("VISUAL"))

    // Create your own environment variable
    os.Setenv("Site", "GoLangCode")
    fmt.Println(os.Getenv("Site"))

    // Equals empty string if doesn't exist
    fmt.Println(os.Getenv("missing"))
}

Leave a Reply

Your email address will not be published. Required fields are marked *