Sobes.tech
Middle+

What are environment variables? Why are they needed?

sobes.tech AI

Answer from AI

Environment variables are key-value pairs set in the operating system and accessible to an application during its runtime. They are used for configuring the application without changing the code, for example, to store database settings, ports, secret keys.

In Go, you can get the value of an environment variable using the os.Getenv function:

package main

import (
    "fmt"
    "os"
)

func main() {
    dbHost := os.Getenv("DB_HOST")
    if dbHost == "" {
        dbHost = "localhost" // default value
    }
    fmt.Println("Database host:", dbHost)
}

This approach allows for easy configuration changes during deployment without modifying the source code, and securely storing secrets outside the repository.