Commit 9e590c3

mo khan <mo@mokhan.ca>
2022-09-24 02:07:45
feat: add helper to fetch env vars
1 parent 759db6e
pkg/env/env.go
@@ -0,0 +1,10 @@
+package env
+
+import "os"
+
+func Fetch(key string, defaultValue string) string {
+	if x := os.Getenv(key); x != "" {
+		return x
+	}
+	return defaultValue
+}
pkg/env/env_test.go
@@ -0,0 +1,23 @@
+package env
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestEnv(t *testing.T) {
+	t.Run("Fetch", func(t *testing.T) {
+		t.Run("returns the environment variable value", func(t *testing.T) {
+			With(Vars{"SECRET": "42"}, func() {
+				assert.Equal(t, "42", Fetch("SECRET", "default"))
+			})
+		})
+
+		t.Run("returns the default value", func(t *testing.T) {
+			With(Vars{"X_VAR": ""}, func() {
+				assert.Equal(t, "default", Fetch("X_VAR", "default"))
+			})
+		})
+	})
+}
pkg/env/vars.go
@@ -0,0 +1,3 @@
+package env
+
+type Vars map[string]string
pkg/env/with.go
@@ -0,0 +1,20 @@
+package env
+
+import "os"
+
+func With(env Vars, callback func()) {
+	original := Vars{}
+
+	for key, value := range env {
+		original[key] = os.Getenv(key)
+		os.Setenv(key, value)
+	}
+
+	defer func(o Vars) {
+		for key, value := range o {
+			os.Setenv(key, value)
+		}
+	}(original)
+
+	callback()
+}