-
Notifications
You must be signed in to change notification settings - Fork 13
/
envfile.go
51 lines (39 loc) · 998 Bytes
/
envfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package util
import (
"bufio"
"bytes"
"io"
"os"
"strings"
"github.com/subosito/gotenv"
)
// LoadEnvFromFile - Loads the environment variables from a file
func LoadEnvFromFile(filename string) error {
if filename != "" {
// have to do filtering before using the gotenv library. While the library trims trailing
// whitespace, a TAB char is no considered whitespace and isn't trimmed. Otherwise, we
// just could have called gotenv.Load and skipped all of this.
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
buf := filterLines(f)
r := bytes.NewReader(buf.Bytes())
return gotenv.Apply(r)
}
return nil
}
func filterLines(r io.Reader) bytes.Buffer {
var lf = []byte("\n")
var out bytes.Buffer
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
// trim out trailing spaces AND tab chars
trimmedLine := strings.TrimRight(line, " \t")
out.Write([]byte(trimmedLine))
out.Write(lf)
}
return out
}