Env File Parser
Parse dotenv files with export prefixes, quoted values, inline comments, and strict key validation, returning a plain map.
Code
package main
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
var envKeyPattern = regexp.MustCompile("^[A-Za-z_][A-Za-z0-9_]*$")
func parseEnvValue(raw string) (string, error) {
if len(raw) >= 2 && raw[0] == '\'' && raw[len(raw)-1] == '\'' {
return raw[1 : len(raw)-1], nil
}
if len(raw) >= 2 && raw[0] == '"' && raw[len(raw)-1] == '"' {
unquoted, err := strconv.Unquote(raw)
if err != nil {
return "", fmt.Errorf("bad quoted value: %w", err)
}
return unquoted, nil
}
if index := strings.Index(raw, " #"); index >= 0 {
raw = strings.TrimSpace(raw[:index])
}
return raw, nil
}
func ParseEnv(data []byte) (map[string]string, error) {
values := make(map[string]string)
for number, raw := range strings.Split(string(data), "\n") {
line := strings.TrimSpace(strings.TrimSuffix(raw, "\r"))
if line == "" || strings.HasPrefix(line, "#") {
continue
}
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
key, value, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("line %d: missing '='", number+1)
}
key = strings.TrimSpace(key)
if !envKeyPattern.MatchString(key) {
return nil, fmt.Errorf("line %d: invalid key %q", number+1, key)
}
parsed, err := parseEnvValue(strings.TrimSpace(value))
if err != nil {
return nil, fmt.Errorf("line %d: %w", number+1, err)
}
values[key] = parsed
}
return values, nil
}
func main() {
document := []byte("# service settings\n" +
"export API_URL=https://api.example.test\n" +
"export APP_NAME=\"Demo \\\"API\\\"\"\n" +
"EMPTY=\n" +
"DB_PASSWORD='p@ss word'\n" +
"PORT=8080 # public port\n")
values, err := ParseEnv(document)
if err != nil {
panic(err)
}
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Printf("%s=%q\n", key, values[key])
}
_, err = ParseEnv([]byte("1BAD=x"))
fmt.Println("invalid key rejected:", err != nil)
}The program step by step
The code’s whole job belongs to the functions parseEnvValue, ParseEnv and main.
One loop does the cycling here: for number, raw := range strings.Split(string(data), "\n"). Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Built-in APIs throughout, which leaves no supply chain to review.
- Handle
errbefore the other return values; that ordering is the whole contract.
Applying it
The defining declaration is func ParseEnv(data []byte) (map[string]string, error)
Each run prints the 1 labeled block invalid key rejected: in source order.
The sequence ParseEnv lives in main; running the file triggers it.
Statements that matter
return nil, fmt.Errorf("line %d: %w", number+1, err)
return "", fmt.Errorf("bad quoted value: %w", err)
return nil, fmt.Errorf("line %d: invalid key %q", number+1, key)
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What is the error handling style?
- As returned `error` values, checked at 3 sites — callers must branch on `err` before using the other return values. When a call fails in the entry flow, the run aborts via `panic(err)`.
- What does Env File Parser print when run?
- The script runs standalone; its 1 labeled outputs include `invalid key rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.