Skip to content

Instantly share code, notes, and snippets.

@kofrasa
Last active July 19, 2018 08:14
Show Gist options
  • Save kofrasa/77824ead27e2b298b0fd6161f2152604 to your computer and use it in GitHub Desktop.
Save kofrasa/77824ead27e2b298b0fd6161f2152604 to your computer and use it in GitHub Desktop.
Load environment variables from file into program
package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
// Source loads variables defined in the path into the current environment
func Source(path string, variables ...string) error {
sb := strings.Builder{}
m := make(map[string]bool, len(variables))
for _, s := range variables {
sb.WriteString(fmt.Sprintf("export %s=$%s; ", s, s))
m[s] = true
}
cmd := exec.Command("sh", "-c", fmt.Sprintf("source %s && %s env", path, sb.String()))
out, err := cmd.Output()
if err != nil {
return err
}
for _, s := range strings.Split(string(out), "\n") {
kv := strings.SplitN(s, "=", 2)
if len(kv) == 2 && m[kv[0]] {
os.Setenv(kv[0], kv[1])
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment