From 41aad458b1876d37e52274b2921739928d7bf83c Mon Sep 17 00:00:00 2001 From: physcik Date: Fri, 8 May 2026 15:11:51 +0500 Subject: Backend settings file --- backend/src/Settings.zig | 78 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 backend/src/Settings.zig (limited to 'backend/src/Settings.zig') diff --git a/backend/src/Settings.zig b/backend/src/Settings.zig new file mode 100644 index 0000000..142a662 --- /dev/null +++ b/backend/src/Settings.zig @@ -0,0 +1,78 @@ +const std = @import("std"); + +const SettingsFile = "Settings.json"; + +pub const errors = error { + Uninitialized +}; + +pub const SettingsStruct = struct { + Port: u16, + + CorsParams: struct { + Origin: []const u8, + Methods: []const u8, + Headers: []const u8, + }, + + RedisParams: struct { + Address: []const u8, + Port: u16, + }, + + DbParams: struct { + Address: []const u8, + Port: u16, + }, +}; + +pub var Current: *SettingsStruct = undefined; + +pub fn ReadConfig(allocator: std.mem.Allocator) !void { + const file = try std.fs.cwd().openFile(SettingsFile, .{}); + defer file.close(); + + const contents = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); + defer allocator.free(contents); + + var parsed = std.json.parseFromSlice( + SettingsStruct, + allocator, + contents, .{}) catch |err| { + std.debug.print("Failed to parse settings: {any}\n", .{err}); + return err; + }; + + defer parsed.deinit(); + + // There is no reason to free this value, it will be freed by OS at the end of the application + Current = try allocator.create(SettingsStruct); + Current.* = .{ + .Port = parsed.value.Port, + + .CorsParams = .{ + .Origin = try allocator.dupe(u8, parsed.value.CorsParams.Origin), + .Methods = try allocator.dupe(u8, parsed.value.CorsParams.Methods), + .Headers = try allocator.dupe(u8, parsed.value.CorsParams.Headers), + }, + + .RedisParams = .{ + .Address = try allocator.dupe(u8, parsed.value.RedisParams.Address), + .Port = parsed.value.RedisParams.Port, + }, + + .DbParams = .{ + .Address = try allocator.dupe(u8, parsed.value.DbParams.Address), + .Port = parsed.value.DbParams.Port, + }, + }; +} + +pub fn Deinit(allocator: std.mem.Allocator) void { + allocator.free(Current.CorsParams.Origin); + allocator.free(Current.CorsParams.Methods); + allocator.free(Current.CorsParams.Headers); + allocator.free(Current.RedisParams.Address); + allocator.free(Current.DbParams.Address); + allocator.destroy(Current); +} -- cgit v1.3