summaryrefslogtreecommitdiff
path: root/backend/src/Settings.zig
blob: 142a66291f32fbe21b555d02fcd8e5899c3d14ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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);
}