check if environment variable is set in go

In Go, you can check if an environment variable is set or not using the os.Getenv() function. This function takes the name of the environment variable as an argument and returns its value. If the environment variable is not set, it returns an empty string.

Here's an example:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Check if the "ENV_VAR" environment variable is set
    envVar := os.Getenv("ENV_VAR")
    if envVar == "" {
        fmt.Println("ENV_VAR is not set")
    } else {
        fmt.Println("ENV_VAR is set to", envVar)
    }
}
286 chars
17 lines

In the above example, we use the os.Getenv() function to check if the environment variable "ENV_VAR" is set. If it is not set, we print a message saying that it is not set. Otherwise, we print a message with its value.

Note that you can also set environment variables in your Go program using the os.Setenv() function.

gistlibby LogSnag