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