env.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. func GetEnvAsStringOrFallback(key, defaultValue string) string {
  19. if v := os.Getenv(key); v != "" {
  20. return v
  21. }
  22. return defaultValue
  23. }
  24. func GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) {
  25. if v := os.Getenv(key); v != "" {
  26. value, err := strconv.Atoi(v)
  27. if err != nil {
  28. return defaultValue, err
  29. }
  30. return value, nil
  31. }
  32. return defaultValue, nil
  33. }
  34. func GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) {
  35. if v := os.Getenv(key); v != "" {
  36. value, err := strconv.ParseFloat(v, 64)
  37. if err != nil {
  38. return defaultValue, err
  39. }
  40. return value, nil
  41. }
  42. return defaultValue, nil
  43. }