os package
The os package contains platform-independent functions for interacting with operating system functionalities. The following code snippets provide a few simple examples of using environment variables.
official docs (opens in a new tab)
Reading Environment Variables
While there are many libraries available for reading environment variables or combining configuration values with environment variables, including managing overrides, there may be cases where you prefer not to download an extra module or include non-built-in modules at all.
In such scenarios, you can utilize the built-in os package in Go.
Here's an example of how to use the os package to read and set environment variables:
package main
import (
"fmt"
"log"
"os"
)
func main() {
// Reading an environment variable by key
path := os.Getenv("PATH")
fmt.Println("PATH:", path)
// Setting environment variables by key
os.Setenv("DB_USERNAME", "my_db_username")
os.Setenv("DB_PASSWORD", "my_secret_db_password")
// Retrieving and printing environment variables
dbUsername := os.Getenv("DB_USERNAME")
fmt.Println("DB_USERNAME:", dbUsername)
// Getting the executable path
executablePath, err := os.Executable()
if err != nil {
log.Fatal(err)
}
// Printing the executable path
fmt.Println("Executable Path:", executablePath)
}In this example:
os.Getenv("PATH")is used to read thePATHenvironment variable.os.Setenv("DB_USERNAME", "my_db_username")andos.Setenv("DB_PASSWORD", "my_secret_db_password")are used to set theDB_USERNAMEandDB_PASSWORDenvironment variables, respectively.os.Executable()is used to get the path of the current executable. This can be useful for determining the directory of your application when it's running.
Using the os package provides a straightforward way to work with environment variables without the need for external dependencies.
You can try out this code snippet here (opens in a new tab).