envconst.Var

This commit is contained in:
Christian Schwarz
2020-04-05 20:12:32 +02:00
parent 8cab6e95ad
commit 4e0574e7d4
2 changed files with 81 additions and 0 deletions
+31
View File
@@ -1,7 +1,10 @@
package envconst
import (
"flag"
"fmt"
"os"
"reflect"
"strconv"
"sync"
"time"
@@ -85,3 +88,31 @@ func String(varname string, def string) string {
cache.Store(varname, e)
return e
}
func Var(varname string, def flag.Value) interface{} {
// use def's type to instantiate a new object of that same type
// and call flag.Value.Set() on it
defType := reflect.TypeOf(def)
if defType.Kind() != reflect.Ptr {
panic(fmt.Sprintf("envconst var must be a pointer, got %T", def))
}
defElemType := defType.Elem()
if v, ok := cache.Load(varname); ok {
return v.(string)
}
e := os.Getenv(varname)
if e == "" {
return def
}
newInstance := reflect.New(defElemType)
if err := newInstance.Interface().(flag.Value).Set(e); err != nil {
panic(err)
}
res := newInstance.Interface()
cache.Store(varname, res)
return res
}