Golang: Reading environment variables

Usually, environment variables are used to provide the configuration information for the program. You can set the environment outside of the program and you can assess these during execution. Go provides the simplest mechanism to access the environment variables. 
You can use 'OS' package to get or set the environment variables.

package main

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

func main() {
	//Read single environment variable value
	val := os.Getenv("WORKING_DIR")
	//Check if the value is set.
	if val != "" {
		fmt.Println("Working Dir is: ", val )
	} else {
		fmt.Println("Working Dir is not set. Setting it now.")
		//You can set env variable using setEnv method.
		os.Setenv("WORKING_DIR", "/root/app_dir")
		fmt.Println("Working Dir is: ", os.Getenv("WORKING_DIR") )
	}

	//You can also iterate over all the environment variables.
	//Here environment variables are returned as string containing varname=value form
	for _, varNVal := range os.Environ() {
		keyVal := strings.SplitN(varNVal, "=", 2)
		fmt.Println("Variable name: " + keyVal[0] + "\tValue: " + keyVal[1] )
	}
}

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...