File size: 1,724 Bytes
d1c38af
 
 
 
 
 
 
 
 
0559038
 
d1c38af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const std = @import("std");
const zap = @import("zap");
const ZigSmartSearch = @import("ZigSmartSearch").ZigSmartSearch;
const database = @embedFile("database.json");
const allocator = std.heap.c_allocator;

var instance: ZigSmartSearch = undefined;

fn on_request(r: zap.Request) !void {
    try r.setHeader("Content-Type", "application/json");
    try r.setHeader("Access-Control-Allow-Origin", "*");
    if (r.query) |the_query| {
        var results = try instance.search(the_query);
        defer results.deinit();
        if (results.items.len == 0) {
            r.sendJson("[]") catch return;
            return;
        }
        const res = try results.toOwnedSlice();
        var arraylist = std.ArrayList(u8).init(allocator);
        errdefer arraylist.deinit();
        try arraylist.append('[');
        for (res) |result| {
            try arraylist.append('"');
            try arraylist.appendSlice(result.doc.get("title").?.string);
            try arraylist.append('"');
            try arraylist.append(',');
        }
        _ = arraylist.pop(); // remove last comma
        try arraylist.append(']');
        const result = try arraylist.toOwnedSlice();
        defer allocator.free(result);
        r.sendJson(result) catch return;
    }
}

pub fn main() !void {
    instance = try ZigSmartSearch.init(
        allocator,
        database,
        ZigSmartSearch.default_config,
    );
    var listener = zap.HttpListener.init(.{
        .port = 7860,
        .on_request = on_request,
        .log = true,
    });
    try listener.listen();

    std.debug.print("Listening on 0.0.0.0:7860\n", .{});

    // start worker threads
    zap.start(.{
        .threads = 2,
        .workers = 2,
    });
}