o
odinpkg.dev
packages / library / odin-dotenv

odin-dotenv

a1de0f9library

A .env parser for odin programming language

No license · updated 1 month ago

odin-dotenv

A simple, generic .env file parser for the Odin programming language.

Installation

Clone the repository or add it as a submodule to your project:

git clone https://github.com/CaetanoGoncalves/odin-dotenv

Or as a submodule:

git submodule add https://github.com/CaetanoGoncalves/odin-dotenv libs/dotenv

Then import it in your code:

import env "libs/dotenv/package/"

Usage

Reading a .env file

values, err := env.read_env(".env")
switch e in err {
case env.Duplicate_Key_Error:
    fmt.printf("duplicate key '%s' at line %d\n", e.key, e.line)
case os.General_Error:
    fmt.printf("file error: %v\n", e)
}
if m, ok := values.?; ok {
    fmt.println(m["API_KEY"])
}

Parsing a string directly

content := "API_KEY=abc123\nDEBUG=true"
values, err := env.parse_env(content)
if err == nil {
    if m, ok := values.?; ok {
        fmt.println(m["API_KEY"])
    }
}

Supported syntax

  • KEY=value
  • export KEY=value
  • KEY="value with quotes"
  • KEY=http://example.com?a=1&b=2 — values with = are handled correctly
  • # comments
  • Empty lines and whitespace-only lines are ignored
  • Duplicate keys return an error with the key name and line number

Error types

Duplicate_Key_Error :: struct {
    key:  string, // the duplicated key
    line: int,    // line number (1-indexed)
}

Env_Error :: union {
    Duplicate_Key_Error,
    os.General_Error,
}

Running tests

odin test tests/
```# odin-dotenv
# odin-dotenv
# odin-dotenv