Get and Set Environment Variables

· 103 words · 1 minute read

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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"))
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!