Menu Close

Go – How to get all the environment variables in go

Here, We will see how to get all environment variables in go. We can do it by using Environ() function in os package in go golang.

Function prototype:

func Environ() []string

Return value:

Environ() function in os package returns
a copy of strings representing the environment, 
in the form "key=value".

Example with code:

package main

import (
  "fmt"
  "os"
  "log"
)

func main() {

  err := os.Setenv("NAME", "Jon")

  if err != nil {

    log.Fatal(err)

  }

  err = os.Setenv("ADDR", "USA")

  if err != nil {

    log.Fatal(err)

  }

  env := os.Environ()

  for _, envs := range env {

    fmt.Println(envs)

  }

}

Output:

TERM_PROGRAM=iTerm.app

TERM=xterm-256color

SHELL=/bin/bash

TMPDIR=/var/folders/9h/

TERM_PROGRAM_VERSION=3.3.9

NAME=Jon

ADDR=USA

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, os, packages

Leave a Reply

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