Environment Variables in Go
Go: Environment Variables
Go provides a simple way to access and manipulate environment variables using the
os
package.
Get the value of an environment variable in Golang
Here's an example of how to get the value of an environment variable:
package main
import (
"fmt"
"os"
)
func main() {
value := os.Getenv("MY_VARIABLE")
if value == "" {
fmt.Println("MY_VARIABLE is not set")
} else {
fmt.Printf("MY_VARIABLE=%s\n", value)
}
}
This code uses the os.Getenv
function to get the value of an environment variable named MY_VARIABLE
. If the variable is not set, the function returns an empty string.
Set the value of an environment variable in Golang
You can also set environment variables using the os.Setenv
function:
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("MY_VARIABLE", "my-value")
value := os.Getenv("MY_VARIABLE")
fmt.Printf("MY_VARIABLE=%s\n", value)
}
This code sets an environment variable named MY_VARIABLE
to the value "my-value"
, then retrieves its value using os.Getenv
and prints it to the console.
Unset the value of an environment variable in Golang
Finally, you can also unset environment variables using the os.Unsetenv
function:
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("MY_VARIABLE", "my-value")
value := os.Getenv("MY_VARIABLE")
fmt.Printf("MY_VARIABLE=%s\n", value)
os.Unsetenv("MY_VARIABLE")
value = os.Getenv("MY_VARIABLE")
if value == "" {
fmt.Println("MY_VARIABLE is not set")
} else {
fmt.Printf("MY_VARIABLE=%s\n", value)
}
}
This code sets an environment variable named MY_VARIABLE
to the value "my-value"
, retrieves its value and prints it, then unsets the variable and confirms that its value is now empty.
I hope that helps you get started with working with environment variables in Go! Let me know if you have any more questions.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go