github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/updater/util/env.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package util 5 6 import ( 7 "os" 8 "strconv" 9 "time" 10 ) 11 12 type envFn func(e string) string 13 14 // EnvDuration returns a duration from an environment variable or default if 15 // invalid or not specified 16 func EnvDuration(envVar string, defaultValue time.Duration) time.Duration { 17 return envDuration(os.Getenv, envVar, defaultValue) 18 } 19 20 func envDuration(fn envFn, envVar string, defaultValue time.Duration) time.Duration { 21 envVal := fn(envVar) 22 if envVal == "" { 23 return defaultValue 24 } 25 duration, err := time.ParseDuration(envVal) 26 if err != nil { 27 return defaultValue 28 } 29 return duration 30 } 31 32 // EnvBool returns a bool from an environment variable or default if invalid or 33 // not specified 34 func EnvBool(envVar string, defaultValue bool) bool { 35 return envBool(os.Getenv, envVar, defaultValue) 36 } 37 38 func envBool(fn envFn, envVar string, defaultValue bool) bool { 39 envVal := fn(envVar) 40 if envVal == "" { 41 return defaultValue 42 } 43 b, err := strconv.ParseBool(envVal) 44 if err != nil { 45 return defaultValue 46 } 47 return b 48 }