-
-
Notifications
You must be signed in to change notification settings - Fork 193
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding support for _FILE fallback to env.Getenv function
Signed-off-by: Dave Henderson <[email protected]>
- Loading branch information
1 parent
20214f5
commit ee7a7cf
Showing
3 changed files
with
155 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,56 @@ | ||
package env | ||
|
||
import "os" | ||
import ( | ||
"io/ioutil" | ||
"os" | ||
|
||
// Getenv retrieves the value of the environment variable named by the key. | ||
// It returns the value, or the default (or an emptry string) if the variable is | ||
// not set. | ||
"github.com/blang/vfs" | ||
) | ||
|
||
// Getenv - retrieves the value of the environment variable named by the key. | ||
// If the variable is unset, but the same variable ending in `_FILE` is set, the | ||
// referenced file will be read into the value. | ||
// Otherwise the provided default (or an emptry string) is returned. | ||
func Getenv(key string, def ...string) string { | ||
val := os.Getenv(key) | ||
return GetenvVFS(vfs.OS(), key, def...) | ||
} | ||
|
||
// GetenvVFS - a convenience function intended for internal use only! | ||
func GetenvVFS(fs vfs.Filesystem, key string, def ...string) string { | ||
val := getenvFile(fs, key) | ||
if val == "" && len(def) > 0 { | ||
return def[0] | ||
} | ||
|
||
return val | ||
} | ||
|
||
func getenvFile(fs vfs.Filesystem, key string) string { | ||
val := os.Getenv(key) | ||
if val != "" { | ||
return val | ||
} | ||
|
||
p := os.Getenv(key + "_FILE") | ||
if p != "" { | ||
val, err := readFile(fs, p) | ||
if err != nil { | ||
return "" | ||
} | ||
return val | ||
} | ||
|
||
return "" | ||
} | ||
|
||
func readFile(fs vfs.Filesystem, p string) (string, error) { | ||
f, err := fs.OpenFile(p, os.O_RDONLY, 0) | ||
if err != nil { | ||
return "", err | ||
} | ||
b, err := ioutil.ReadAll(f) | ||
if err != nil { | ||
return "", err | ||
} | ||
return string(b), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters