2016-08-03 22:06:50 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2016-08-04 20:41:04 +00:00
|
|
|
// OsFetcher is an implementation of the Fetcher type for communicating with
|
2016-08-03 22:06:50 +00:00
|
|
|
// the system's environment.
|
|
|
|
//
|
|
|
|
// It is safe to use across multiple goroutines.
|
2016-08-04 20:41:04 +00:00
|
|
|
type OsFetcher struct {
|
2016-08-03 22:06:50 +00:00
|
|
|
// vmu guards read/write access to vals
|
|
|
|
vmu sync.Mutex
|
|
|
|
// vals maintains a local cache of the system's enviornment variables
|
|
|
|
// for fast repeat lookups of a given key.
|
2016-08-05 21:59:57 +00:00
|
|
|
vals map[string]*string
|
2016-08-03 22:06:50 +00:00
|
|
|
}
|
|
|
|
|
2016-08-04 20:41:04 +00:00
|
|
|
// NewOsFetcher returns a new *OsFetcher.
|
|
|
|
func NewOsFetcher() *OsFetcher {
|
|
|
|
return &OsFetcher{
|
2016-08-05 21:59:57 +00:00
|
|
|
vals: make(map[string]*string),
|
2016-08-03 22:06:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns the value associated with the given key as stored in the local
|
|
|
|
// cache, or in the operating system's environment variables.
|
|
|
|
//
|
|
|
|
// If there was a cache-hit, the value will be returned from the cache, skipping
|
|
|
|
// a check against os.Getenv. Otherwise, the value will be fetched from the
|
|
|
|
// system, stored in the cache, and then returned. If no value was present in
|
|
|
|
// the cache or in the system, an empty string will be returned.
|
|
|
|
//
|
|
|
|
// Get is safe to call across multiple goroutines.
|
2016-08-05 21:59:57 +00:00
|
|
|
func (o *OsFetcher) Get(key string) (val string, ok bool) {
|
2016-08-04 20:41:04 +00:00
|
|
|
o.vmu.Lock()
|
|
|
|
defer o.vmu.Unlock()
|
2016-08-03 22:06:50 +00:00
|
|
|
|
2016-08-04 20:41:04 +00:00
|
|
|
if i, ok := o.vals[key]; ok {
|
2016-08-05 21:59:57 +00:00
|
|
|
if i == nil {
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
return *i, true
|
2016-08-03 22:06:50 +00:00
|
|
|
}
|
|
|
|
|
2016-08-05 21:59:57 +00:00
|
|
|
v, ok := os.LookupEnv(key)
|
|
|
|
if ok {
|
|
|
|
o.vals[key] = &v
|
|
|
|
} else {
|
|
|
|
o.vals[key] = nil
|
|
|
|
}
|
2016-08-03 22:06:50 +00:00
|
|
|
|
2016-08-05 21:59:57 +00:00
|
|
|
return v, ok
|
2016-08-03 22:06:50 +00:00
|
|
|
}
|