0

How I can rewrite the below code so that whenever I use the var CsvVersion every time it calls the func and gives me the latest value?

package main

import (
    "fmt"
    "os"
)

var (
    DefaultValMap = map[string]string{
        "CSV_VERSION": "v1",
    }

    CsvVersion = GetEnvOrDefault("CSV_VERSION")
)

func GetEnvOrDefault(env string) string {
    if val := os.Getenv(env); val != "" {
        return val
    }

    return DefaultValMap[env]
}

func main() {
    fmt.Println(CsvVersion)
    os.Setenv("CSV_VERSION", "v2")
    fmt.Println(CsvVersion)
    fmt.Println(os.Getenv("CSV_VERSION"))
}

Actual output

$ go build 1.go && ./1 
v1
v1
v2

The output should be like this

$ go build 1.go && ./1 
v1
v2
v2
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

8

There is no way to do this exact thing in Go. Go, very much by design, avoids "magic" things like this. Instead, don't use a variable, use a function:

func CsvVersion() string {
    return GetEnvOrDefault("CSV_VERSION")
}

However note: It's not (generally) possible to change environment variables after a program starts (except within the program itself, which has very limited utility), so checking an env variable on every use is usually just wasted effort. Read more about that here.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189