Sling Academy
Home/Golang/Working with Environment Variables in Go Using the `os` Package

Working with Environment Variables in Go Using the `os` Package

Last updated: November 26, 2024

Environment variables play a critical role in applications, allowing developers to manage configuration settings external to the code. In Go, the os package is one of the most efficient ways to interact with these environment variables.

Accessing Environment Variables

To access an environment variable in Go, you use the os.Getenv function. This function retrieves the value of the environment variable passed as a string.

package main

import (
    "fmt"
    "os"
)

func main() {
    home := os.Getenv("HOME")
    fmt.Println("Home directory:", home)
}

The above code snippet retrieves the value of the HOME environment variable and prints it to the console.

Setting Environment Variables

While typically environmental variables are set outside of the application (e.g., in your shell configuration), you can set an environment variable for the duration of the program using the os.Setenv function.

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Setenv("GREETING", "Hello, World!")
    if err != nil {
        fmt.Println("Error setting environment variable:", err)
        return
    }

    greeting := os.Getenv("GREETING")
    fmt.Println(greeting)
}

In this example, we set an environment variable named GREETING.

Listing All Environment Variables

To get a list of all environment variables, Go provides the os.Environ function, which returns a slice of strings in the format "key=value".

package main

import (
    "fmt"
    "os"
)

func main() {
    envs := os.Environ()
    for _, env := range envs {
        fmt.Println(env)
    }
}

Deleting Environment Variables

If you need to remove an environment variable within a Go application, you can do so using the os.Unsetenv function.

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Unsetenv("GREETING")
    if err != nil {
        fmt.Println("Error unsetting environment variable:", err)
    }
    greeting := os.Getenv("GREETING")
    fmt.Println("Unset GREETING, new value:", greeting)
}

This function removes the GREETING variable, and subsequent calls to os.Getenv("GREETING") will return an empty string.

Conclusion

Working with environment variables in Go is straightforward with the os package. Whether you need to retrieve, set, list, or delete them, the os package provides robust functions to handle these common use cases efficiently within any Go application.

Next Article: Understanding the `time` Package for Date and Time Manipulation in Go

Previous Article: Handling Files and Directories Using the `os` Package in Go

Series: Working with Core package in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant