From 23979c3ad48389f36721410a3e75885c660cefab Mon Sep 17 00:00:00 2001 From: Lorenzo Villani Date: Tue, 9 Jun 2015 22:37:28 +0200 Subject: [PATCH] Add EnvironMap() that converts os.Environ() output to a map --- os.go | 22 +++++++++++++++++++++- os_test.go | 19 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/os.go b/os.go index c71df8c..d7197f1 100644 --- a/os.go +++ b/os.go @@ -1,6 +1,26 @@ package dry -import "os" +import ( + "os" + "strings" +) + +// EnvironMap returns the current environment variables as a map. +func EnvironMap() map[string]string { + return environToMap(os.Environ()) +} + +func environToMap(environ []string) map[string]string { + ret := make(map[string]string) + + for _, v := range environ { + parts := strings.SplitN(v, "=", 2) + + ret[parts[0]] = parts[1] + } + + return ret +} // GetenvDefault retrieves the value of the environment variable // named by the key. It returns the given defaultValue if the diff --git a/os_test.go b/os_test.go index 4a6d218..b704a4f 100644 --- a/os_test.go +++ b/os_test.go @@ -2,6 +2,25 @@ package dry import "testing" +func TestEnvironMap(t *testing.T) { + ret := environToMap([]string{ + "a=b", + "b=c=d", + }) + + if len(ret) != 2 { + t.Fail() + } + + if ret["a"] != "b" { + t.Fail() + } + + if ret["b"] != "c=d" { + t.Fail() + } +} + func TestGetenvDefault(t *testing.T) { if GetenvDefault("GO_DRY_BOGUS_ENVIRONMENT_VARIABLE", "default") != "default" { t.Fail()