wttr/zig/src/config.zig

48 lines
2.2 KiB
Zig

const std = @import("std");
pub const Config = struct {
listen_host: []const u8,
listen_port: u16,
cache_size: usize,
cache_dir: []const u8,
geolite_path: []const u8,
geolocator_url: []const u8,
pub fn load(allocator: std.mem.Allocator) !Config {
return Config{
.listen_host = std.process.getEnvVarOwned(allocator, "WTTR_LISTEN_HOST") catch try allocator.dupe(u8, "0.0.0.0"),
.listen_port = blk: {
const port_str = std.process.getEnvVarOwned(allocator, "WTTR_LISTEN_PORT") catch break :blk 8002;
defer allocator.free(port_str);
break :blk std.fmt.parseInt(u16, port_str, 10) catch 8002;
},
.cache_size = blk: {
const size_str = std.process.getEnvVarOwned(allocator, "WTTR_CACHE_SIZE") catch break :blk 10_000;
defer allocator.free(size_str);
break :blk std.fmt.parseInt(usize, size_str, 10) catch 10_000;
},
.cache_dir = std.process.getEnvVarOwned(allocator, "WTTR_CACHE_DIR") catch try allocator.dupe(u8, "/tmp/wttr-cache"),
.geolite_path = std.process.getEnvVarOwned(allocator, "WTTR_GEOLITE_PATH") catch try allocator.dupe(u8, "./GeoLite2-City.mmdb"),
.geolocator_url = std.process.getEnvVarOwned(allocator, "WTTR_GEOLOCATOR_URL") catch try allocator.dupe(u8, "http://localhost:8004"),
};
}
pub fn deinit(self: Config, allocator: std.mem.Allocator) void {
allocator.free(self.listen_host);
allocator.free(self.cache_dir);
allocator.free(self.geolite_path);
allocator.free(self.geolocator_url);
}
};
test "config loads defaults" {
const allocator = std.testing.allocator;
const cfg = try Config.load(allocator);
defer cfg.deinit(allocator);
try std.testing.expectEqualStrings("0.0.0.0", cfg.listen_host);
try std.testing.expectEqual(@as(u16, 8002), cfg.listen_port);
try std.testing.expectEqual(@as(usize, 10_000), cfg.cache_size);
try std.testing.expectEqualStrings("./GeoLite2-City.mmdb", cfg.geolite_path);
try std.testing.expectEqualStrings("http://localhost:8004", cfg.geolocator_url);
}