rano/config/dotenv/read.go
Ankit Patial 45c318b897 - graph, dotenv read
- graph, cors and secure header
- web, urql client basic setup
2024-11-04 11:35:43 +05:30

70 lines
1.4 KiB
Go

package dotenv
import (
"bytes"
"io"
"os"
)
//
// copied from https://github.com/joho/godotenv/blob/main/godotenv.go
//
// Read all env (with same file loading semantics as Load) but return values as
// a map rather than automatically writing values into env
func Read(filenames ...string) (envMap map[string]string, err error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename)
if individualErr != nil {
err = individualErr
return // return early on a spazout
}
for key, value := range individualEnvMap {
envMap[key] = value
}
}
return
}
func filenamesOrDefault(filenames []string) []string {
if len(filenames) == 0 {
return []string{".env"}
}
return filenames
}
func readFile(filename string) (envMap map[string]string, err error) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
return parse(file)
}
// parse reads an env file from io.Reader, returning a map of keys and values.
func parse(r io.Reader) (map[string]string, error) {
var buf bytes.Buffer
_, err := io.Copy(&buf, r)
if err != nil {
return nil, err
}
return unmarshal(buf.Bytes())
}
// unmarshal parses env file from byte slice of chars, returning a map of keys and values.
func unmarshal(src []byte) (map[string]string, error) {
out := make(map[string]string)
err := parseBytes(src, out)
return out, err
}