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


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 (

func main() {

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

  if err != nil {



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

  if err != nil {



  name := os.Getenv("NAME")

  addr := os.Getenv("ADDR")

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



Name: Jon, Addr: USA

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

Posted in golang, os

Leave a Reply

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