Menu Close

Go – How to get environment variable value in go

Here, We will learn how to get environment variable value in go. We can do it by using Getenv() function in os package in go golang.

Function prototype:

func Getenv(str string) string

Paramters:

str: Environment variable name

Return value:

Getenv() function in os package returns 
the value of the environment variable named 
by the str.
If the environment variable is not set then it 
return empty.

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)

  }

  name := os.Getenv("NAME")

  addr := os.Getenv("ADDR")

  fmt.Printf("Name: %s, Addr: %s\n", name, addr)

}

Output:

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

Leave a Reply

Your email address will not be published.

Contact Us