Obtaining Environment Variables with Go

Cihan Ozhan
2 min readNov 9, 2021

Obtaining Environment Variables with Go

I wrote this code in 2016 but re-shared it for newbies.

While developing an application, we need to access the environment variables that are predefined in the computer system. There can be many reasons for this… For example, we may want to obtain basic information about the processor architecture, computer name, domain name or a predefined PATH information (JAVA_HOME, GOPATH, etc.) directly from the system, not from the framework we use. In this case, we must obtain all the environment variables or directly get that part with the names defined in these variables. In the Go programming language, this is quite simple.

package main

import (
"fmt"
"os"
)

func main() {

for _, env := range os.Environ() {
fmt.Println(env)
}
}

When you run the above shortcode, all the environment variables defined on your computer will be listed one below the other.

What if we want to get a specific environment variable? For example GOPATH or computer username…

package main
import (
"fmt"
"os"
)

func main() {
uName := os.Getenv("USERNAME")
uDomain := os.Getenv("USERDOMAIN")
processorAchitecture := os.Getenv("PROCESSOR_ARCHITECTURE")
processorIdentifier := os.Getenv("PROCESSOR_IDENTIFIER")
processorLevel := os.Getenv("PROCESSOR_LEVEL")
goRoot := os.Getenv("GOROOT")
goPath := os.Getenv("GOPATH")
homePath := os.Getenv("HOMEPATH")

fmt.Println("Username : " + uName)
fmt.Println("Domain : " + uDomain)
fmt.Println("Process Architecture: " + processorAchitecture)
fmt.Println("Process ID : " + processorIdentifier)
fmt.Println("Process Level : " + processorLevel)
fmt.Println("-> other...")
fmt.Println("HOMEPATH : " + homePath)
fmt.Println("GOPATH : " + goPath)
fmt.Println("GOROOT : " + goRoot)
}

You can use the commands below to test the data coming directly from the console.

echo %USERNAME%
echo %GOPATH%

Good luck!
Cihan Özhan

--

--