Created
November 19, 2022 12:00
-
-
Save ndabAP/c0a4f001c6ad28a31e60aa9d3691b8ef to your computer and use it in GitHub Desktop.
Dependency-free .env resolver in Go. Variables are exposed as environmental variables
This file contains hidden or 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
// cmd/main.go | |
package main | |
import ( | |
"bufio" | |
"errors" | |
"os" | |
"path/filepath" | |
"runtime" | |
"strings" | |
"syscall" | |
) | |
func init() { | |
if err := setdotenvs(); err != nil { | |
panic(err) | |
} | |
} | |
func setdotenvs() error { | |
_, filename, _, ok := runtime.Caller(1) | |
if !ok { | |
return errors.New("can't get current filename") | |
} | |
dirname := filepath.Dir(filename) | |
file, err := os.Open(dirname + "/../" + ".env") | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
scanner := bufio.NewScanner(file) | |
for scanner.Scan() { | |
kv := strings.Split(scanner.Text(), "=") | |
if len(kv) != 2 { | |
continue | |
} | |
key, value := kv[0], kv[1] | |
if err := os.Setenv(key, value); err != nil { | |
return err | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment