Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add func "LoadString" #75

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion godotenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,28 @@ func Load(filenames ...string) (err error) {
return
}

// LoadString will read your string like env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
//
// You can to override an env variable if you want using overload value.
func LoadString(envString string, overload bool) (err error) {
currentEnv := map[string]bool{}
rawEnv := os.Environ()
for _, rawEnvLine := range rawEnv {
key := strings.Split(rawEnvLine, "=")[0]
currentEnv[key] = true
}

loadedEnv, _ := Unmarshal(envString)
for key, value := range loadedEnv {
if !currentEnv[key] || overload {
os.Setenv(key, value)
}
}
return
}

// Overload will read your env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
Expand Down Expand Up @@ -258,7 +280,7 @@ func parseLine(line string, envMap map[string]string) (key string, value string,
}
key = strings.TrimSpace(key)

re := regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
re := regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
key = re.ReplaceAllString(splitString[0], "$1")

// Parse the value
Expand Down