Hello, is anyone aware of any problems with accessing environment variables using Golang under macOS. I’m trying to use the github.com/kelseyhightower/envconfig package. According to the documentation, I should be able to set various variables such as:
package main
import (
"fmt"
"log"
"time"
"github.com/kelseyhightower/envconfig"
)
type Specification struct {
Debug bool
Port int
User string
Users []string
Rate float32
Timeout time.Duration
ColorCodes map[string]int
}
func main() {
var s Specification
err := envconfig.Process("myapp", &s)
if err != nil {
log.Fatal(err.Error())
}
format := "Debug: %v\nPort: %d\nUser: %s\nRate: %f\nTimeout: %s\n"
_, err = fmt.Printf(format, s.Debug, s.Port, s.User, s.Rate, s.Timeout)
if err != nil {
log.Fatal(err.Error())
}
fmt.Println("Users:")
for _, u := range s.Users {
fmt.Printf(" %s\n", u)
}
fmt.Println("Color codes:")
for k, v := range s.ColorCodes {
fmt.Printf(" %s: %d\n", k, v)
}
}
It steadfastly refuses to work. Only the zero-values of the struct are returned. I seem to remember I had some issues when I tried to use os.Getenv - I was hoping that this package would correct these problems.
What shell are you using? I experience this kind of problem with the fish shell on macOS. I cannot remember having seen this with Bash (I am using a homebrew'ed Bash 4.4 instead of the built-in Bash 3.2.)
And since you are using envconfig: Did you also try native os.Getenv() (to rule out an issue with envconfig)?
Works fine on Mac, of course, although I haven’t used this 3rd party stuff but os.Getenv. Be sure that you export variables in the same shell where your Go executes. This is about UNIX alike systems, not about Mac.
When you you execute that file it is run in a subshell, the environment is changed only in this subshell and then this subshell will exit in the very same moment as your script exits.
You need to either run those exports directly or source the file, which means that it is run in the current shell and the environment will persist after the script has finished.