How to set environment variables using the os package in Golang?

To set environment variables using the os package in Golang, you can use the Setenv function provided by the package. Here's an example of how to do it:

package main import ( "fmt" "os" ) func main() { // Setting a single environment variable os.Setenv("ENV_NAME", "example_value") // Setting multiple environment variables envVars := map[string]string{ "ENV_VAR_1": "value_1", "ENV_VAR_2": "value_2", "ENV_VAR_3": "value_3", } for key, value := range envVars { os.Setenv(key, value) } // Getting and printing the value of an environment variable envValue := os.Getenv("ENV_NAME") fmt.Println("ENV_NAME:", envValue) }

In this example, we first set a single environment variable "ENV_NAME" with the value "example_value" using os.Setenv.

Next, we set multiple environment variables using the Setenv function inside a loop. We define the environment variables in a map where the key represents the name of the environment variable and the value represents its value.

To retrieve the value of an environment variable, we use os.Getenv and pass the name of the environment variable as an argument.

Finally, we print the value of the "ENV_NAME" environment variable.

Remember to import the os and fmt packages before using them in your code.