env.go 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package env
  2. import (
  3. "os"
  4. "testing"
  5. )
  6. type Env interface {
  7. Get(key string) string
  8. Env() []string
  9. }
  10. type osEnv struct{}
  11. // Get implements Env.
  12. func (o *osEnv) Get(key string) string {
  13. return os.Getenv(key)
  14. }
  15. func (o *osEnv) Env() []string {
  16. env := os.Environ()
  17. if len(env) == 0 {
  18. return nil
  19. }
  20. return env
  21. }
  22. func New() Env {
  23. if testing.Testing() {
  24. return NewFromMap(nil)
  25. }
  26. return &osEnv{}
  27. }
  28. type mapEnv struct {
  29. m map[string]string
  30. }
  31. // Get implements Env.
  32. func (m *mapEnv) Get(key string) string {
  33. if value, ok := m.m[key]; ok {
  34. return value
  35. }
  36. return ""
  37. }
  38. // Env implements Env.
  39. func (m *mapEnv) Env() []string {
  40. if len(m.m) == 0 {
  41. return nil
  42. }
  43. env := make([]string, 0, len(m.m))
  44. for k, v := range m.m {
  45. env = append(env, k+"="+v)
  46. }
  47. return env
  48. }
  49. func NewFromMap(m map[string]string) Env {
  50. if m == nil {
  51. m = make(map[string]string)
  52. }
  53. return &mapEnv{m: m}
  54. }