| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "sync" |
| 6 | ) |
| 7 | |
| 8 | // OsFetcher is an implementation of the Fetcher type for communicating with |
| 9 | // the system's environment. |
| 10 | // |
| 11 | // It is safe to use across multiple goroutines. |
| 12 | type OsFetcher struct { |
| 13 | // vmu guards read/write access to vals |
| 14 | vmu sync.Mutex |
| 15 | // vals maintains a local cache of the system's environment variables |
| 16 | // for fast repeat lookups of a given key. |
| 17 | vals map[string]*string |
| 18 | } |
| 19 | |
| 20 | // NewOsFetcher returns a new *OsFetcher. |
| 21 | func NewOsFetcher() *OsFetcher { |
| 22 | return &OsFetcher{ |
| 23 | vals: make(map[string]*string), |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // Get returns the value associated with the given key as stored in the local |
| 28 | // cache, or in the operating system's environment variables. |
| 29 | // |
| 30 | // If there was a cache-hit, the value will be returned from the cache, skipping |
| 31 | // a check against os.Getenv. Otherwise, the value will be fetched from the |
| 32 | // system, stored in the cache, and then returned. If no value was present in |
| 33 | // the cache or in the system, an empty string will be returned. |
| 34 | // |
| 35 | // Get is safe to call across multiple goroutines. |
| 36 | func (o *OsFetcher) Get(key string) (val string, ok bool) { |
| 37 | o.vmu.Lock() |
| 38 | defer o.vmu.Unlock() |
| 39 | |
| 40 | if i, ok := o.vals[key]; ok { |
| 41 | if i == nil { |
| 42 | return "", false |
| 43 | } |
| 44 | return *i, true |
| 45 | } |
| 46 | |
| 47 | v, ok := os.LookupEnv(key) |
| 48 | if ok { |
| 49 | o.vals[key] = &v |
| 50 | } else { |
| 51 | o.vals[key] = nil |
| 52 | } |
| 53 | |
| 54 | return v, ok |
| 55 | } |
| 56 | |
| 57 | // GetAll implements the `config.Fetcher.GetAll` method by returning, at most, a |
| 58 | // 1-ary set containing the result of `config.OsFetcher.Get()`. |
| 59 | func (o *OsFetcher) GetAll(key string) []string { |
| 60 | if v, ok := o.Get(key); ok { |
| 61 | return []string{v} |
| 62 | } |
| 63 | return make([]string, 0) |
| 64 | } |
| 65 | |
| 66 | func (o *OsFetcher) All() map[string][]string { |
| 67 | return nil |
| 68 | } |