Sling Academy
Home/Golang/How to use environment variables in Go

How to use environment variables in Go

Last updated: November 26, 2024

Environment variables are a common way to configure applications outside of the source code. In Go, these can be easily managed using the os package. This article will guide you through managing environment variables within a Go program.

Setting Environment Variables

Before accessing environment variables in your Go application, you need to set them in your system. This can be done via the command line for testing purposes.

export MY_ENV_VAR=somevalue

In Unix-like systems, such as Linux and macOS, the above command will set an environment variable called MY_ENV_VAR with the value somevalue.

Accessing Environment Variables in Go

The Go os package provides functions to read and handle environment variables. The most common method is os.Getenv, which retrieves the value of the environment variable named by the key.

package main

import (
    "fmt"
    "os"
)

func main() {
    myEnvVar := os.Getenv("MY_ENV_VAR")
    fmt.Println("MY_ENV_VAR:", myEnvVar)
}

In this example, the os.Getenv function is used to get the value of MY_ENV_VAR. If the variable is not set, it will return an empty string.

Checking for Environment Variable Existence

Since os.Getenv returns an empty string if the environment variable does not exist or is empty, it might be useful to confirm if an environment variable is set.

package main

import (
    "fmt"
    "os"
)

func main() {
    if value, exists := os.LookupEnv("MY_ENV_VAR"); exists {
        fmt.Println("MY_ENV_VAR:", value)
    } else {
        fmt.Println("MY_ENV_VAR is not set")
    }
}

Here, os.LookupEnv not only returns the value of the variable but also a boolean indicating its presence, allowing us to respond accordingly if it's not set.

Setting Environment Variables in Go

Setting an environment variable at runtime can be useful in certain scenarios. The os.Setenv function allows you to set an environment variable.

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Setenv("NEW_ENV_VAR", "value")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("NEW_ENV_VAR set to:", os.Getenv("NEW_ENV_VAR"))
}

Although you can set environment variables this way, it's important to note that changes are only available for the current process and its child processes.

Conclusion

Managing environment variables in Go is straightforward with the use of the os package. These capabilities allow you to tailor your app configurations without modifying the source code, facilitating easier application support and greater flexibility across different environments.

Previous Article: How to get the current process ID in Go

Series: File I/O and Operating System Interaction

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