Golang – Environment Variables
An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.
In Golang, we can use the os package to read and write environment variables.
1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.
os.Setenv(key,value)
2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.
os.Getenv(key)
3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.
os.Unsetenv(key)
4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.
os.LookupEnv(key)
5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format.
os.Environ()
6. Delete all environment variables with os.Clearenv().
os.Clearenv()
Example 1:
Go
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv( "GEEKS" , "geeks" )
fmt.Println( "GEEKS:" , os.Getenv( "GEEKS" ))
os.Unsetenv( "GEEKS" )
value, ok := os.LookupEnv( "GEEKS" )
fmt.Println( "GEEKS:" , value, " Is present:" , ok)
}
|
Output:
Example 2:
Go
package main
import (
"fmt"
"os"
)
func main() {
for _, env := range os.Environ() {
fmt.Println(env)
}
}
|
Output:
Example 3:
Go
package main
import (
"fmt"
"os"
)
func main() {
os.Clearenv()
fmt.Println( "All environment variables cleared" )
}
|
Output:
All environment variables cleared
Last Updated :
04 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...