env.go 833 B

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