BeigeHornet151/zig-dotenv
A lightweight .env file parser for Zig - Load environment variables from .env files with zero dependencies
A simple and lightweight .env
file parser for Zig applications. Parse environment configuration files with minimal overhead and zero external dependencies.
.env
file format and conventionsAdd this repository as a dependency in your build.zig.zon
:
.{
.name = "your-project",
.version = "0.1.0",
.dependencies = .{
.dotenv = .{
.url = "https://github.com/BeigeHornet151/zig-dotenv/archive/main.tar.gz",
.hash = "12200000000000000000000000000000000000000000000000000000000000000000", // Use zig fetch to get actual hash
},
},
}
Alternatively, you can copy src/dotenv.zig
directly into your project.
const std = @import("std");
const dotenv = @import("dotenv");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Load .env file
var env = try dotenv.DotEnv.loadFile(allocator, ".env");
defer env.deinit();
// Get values
const db_url = env.get("DATABASE_URL") orelse "default_db_url";
const api_key = env.get("API_KEY") orelse "no_key";
std.debug.print("Database URL: {s}\n", .{db_url});
std.debug.print("API Key: {s}\n", .{api_key});
}
# Database configuration
DATABASE_URL=postgres://localhost:5432/myapp
DATABASE_POOL_SIZE=10
# API settings
API_KEY=your_secret_key_here
API_TIMEOUT=30
# Feature flags
DEBUG=true
ENABLE_LOGGING=false
# Quoted values
WELCOME_MESSAGE="Hello, World!"
SINGLE_QUOTED='Also works'
The parser handles standard .env
file format:
KEY=value
#
are ignored"double"
and 'single'
quotes are supported and strippedDotEnv
Main struct for loading and accessing environment variables.
loadFile(allocator: Allocator, path: []const u8) !DotEnv
.env
file from the specified pathDotEnvError.FileNotFound
if the file doesn't existget(key: []const u8) ?[]const u8
null
if the key doesn't existdeinit()
Run the tests:
zig test test.zig
Contributions are welcome. Please:
Released under the MIT License. See the LICENSE file for details.
.env
file parsing