-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource_dotenv.go
52 lines (40 loc) · 874 Bytes
/
source_dotenv.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
52
package enver
import (
"fmt"
"os"
"strings"
)
const (
Type_DotEnv = "dotenv"
)
type Source_DotEnv struct {
Path string
}
func (s *Source_DotEnv) Type() string {
return Type_DotEnv
}
func (s *Source_DotEnv) Get() (map[string]any, error) {
return s.readDotEnvFile(s.Path)
}
func (s *Source_DotEnv) readDotEnvFile(path string) (map[string]any, error) {
if path == "" {
path = ".env"
}
pairs := make(map[string]any)
data, err := os.ReadFile(path)
if err != nil {
return pairs, fmt.Errorf("failed to read .env file: %w", err)
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
if line == "" {
continue
}
parts := strings.Split(line, "=")
if len(parts) != 2 {
return pairs, fmt.Errorf("invalid .env file format. Expected key=value format, got: %s", line)
}
pairs[parts[0]] = parts[1]
}
return pairs, nil
}