env.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "os"
  16. )
  17. // Getenver is the interface we use to mock out the env for easier testing. OS env
  18. // vars can't be as easily tested since internally it uses sync.Once.
  19. type Getenver interface {
  20. Getenv(string) string
  21. }
  22. // osEnv uses the actual os.Getenv methods to lookup values.
  23. type osEnv struct{}
  24. // Getenv gets the value of the requested environment variable.
  25. func (*osEnv) Getenv(s string) string {
  26. return os.Getenv(s)
  27. }
  28. // explicitEnv uses a map instead of os.Getenv methods to lookup values.
  29. type explicitEnv struct {
  30. vals map[string]string
  31. }
  32. // Getenv returns the value of the requested environment variable (in this
  33. // implementation, really just a map lookup).
  34. func (e *explicitEnv) Getenv(s string) string {
  35. return e.vals[s]
  36. }
  37. // defaultOSEnv uses a Getenver to lookup values but if it does
  38. // not have that value, it falls back to its internal set of defaults.
  39. type defaultEnver struct {
  40. firstChoice Getenver
  41. defaults map[string]string
  42. }
  43. // Getenv returns the value of the environment variable or its default if unset.
  44. func (e *defaultEnver) Getenv(s string) string {
  45. v := e.firstChoice.Getenv(s)
  46. if len(v) == 0 {
  47. return e.defaults[s]
  48. }
  49. return v
  50. }
  51. func envWithDefaults(defaults map[string]string) Getenver {
  52. return &defaultEnver{firstChoice: &osEnv{}, defaults: defaults}
  53. }