List Environment Variables in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
  
    // Use os.Environ to list all key/value pairs in the environment.
    // This returns a slice of strings in the form KEY=value.
    // You can strings.SplitN them to get the key and value. Here we print all the keys.
    for _, e := range os.Environ() {
        pair := strings.SplitN(e, "=", 2)
        fmt.Println(pair[0])
    }
}