env.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. Copyright 2015 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 env
  14. import (
  15. "os"
  16. "strconv"
  17. )
  18. // GetEnvAsStringOrFallback returns the env variable for the given key
  19. // and falls back to the given defaultValue if not set
  20. func GetEnvAsStringOrFallback(key, defaultValue string) string {
  21. if v := os.Getenv(key); v != "" {
  22. return v
  23. }
  24. return defaultValue
  25. }
  26. // GetEnvAsIntOrFallback returns the env variable (parsed as integer) for
  27. // the given key and falls back to the given defaultValue if not set
  28. func GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) {
  29. if v := os.Getenv(key); v != "" {
  30. value, err := strconv.Atoi(v)
  31. if err != nil {
  32. return defaultValue, err
  33. }
  34. return value, nil
  35. }
  36. return defaultValue, nil
  37. }
  38. // GetEnvAsFloat64OrFallback returns the env variable (parsed as float64) for
  39. // the given key and falls back to the given defaultValue if not set
  40. func GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) {
  41. if v := os.Getenv(key); v != "" {
  42. value, err := strconv.ParseFloat(v, 64)
  43. if err != nil {
  44. return defaultValue, err
  45. }
  46. return value, nil
  47. }
  48. return defaultValue, nil
  49. }