env.go 636 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package proc
  2. import (
  3. "os"
  4. "strconv"
  5. "sync"
  6. )
  7. var (
  8. envs = make(map[string]string)
  9. envLock sync.RWMutex
  10. )
  11. // Env returns the value of the given environment variable.
  12. func Env(name string) string {
  13. envLock.RLock()
  14. val, ok := envs[name]
  15. envLock.RUnlock()
  16. if ok {
  17. return val
  18. }
  19. val = os.Getenv(name)
  20. envLock.Lock()
  21. envs[name] = val
  22. envLock.Unlock()
  23. return val
  24. }
  25. // EnvInt returns an int value of the given environment variable.
  26. func EnvInt(name string) (int, bool) {
  27. val := Env(name)
  28. if len(val) == 0 {
  29. return 0, false
  30. }
  31. n, err := strconv.Atoi(val)
  32. if err != nil {
  33. return 0, false
  34. }
  35. return n, true
  36. }