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