Skip to content

Commit 7b79969

Browse files
authored
improvement (#9407)
1 parent dae5a79 commit 7b79969

File tree

4 files changed

+29
-63
lines changed

4 files changed

+29
-63
lines changed

frameworks/Zig/httpz/.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
zig-cache/**/*',
2-
zig-out: 'zig-out/**/*',
1+
.zig-cache
2+
zig-out

frameworks/Zig/httpz/build.zig

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,23 @@
11
const std = @import("std");
2-
const ModuleMap = std.StringArrayHashMap(*std.Build.Module);
3-
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
4-
const allocator = gpa.allocator();
52

6-
// Although this function looks imperative, note that its job is to
7-
// declaratively construct a build graph that will be executed by an external
8-
// runner.
93
pub fn build(b: *std.Build) !void {
10-
// Standard target options allows the person running `zig build` to choose
11-
// what target to build for. Here we do not override the defaults, which
12-
// means any target is allowed, and the default is native. Other options
13-
// for restricting supported target set are available.
144
const target = b.standardTargetOptions(.{});
15-
16-
// Standard optimization options allow the person running `zig build` to select
17-
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do nots
18-
// set a preferred release mode, allowing the user to decide how to optimize.
195
const optimize = b.standardOptimizeOption(.{});
206

217
const dep_opts = .{ .target = target, .optimize = optimize };
228

239
const exe = b.addExecutable(.{
2410
.name = "httpz",
25-
// In this case the main source file is merely a path, however, in more
26-
// complicated build scripts, this could be a generated file.
2711
.root_source_file = b.path("src/main.zig"),
2812
.target = target,
2913
.optimize = optimize,
3014
});
3115

32-
var modules = ModuleMap.init(allocator);
33-
defer modules.deinit();
34-
3516
const httpz_module = b.dependency("httpz", dep_opts).module("httpz");
3617
const pg_module = b.dependency("pg", dep_opts).module("pg");
3718
const datetimez_module = b.dependency("datetimez", dep_opts).module("zig-datetime");
3819
const mustache_module = b.dependency("mustache", dep_opts).module("mustache");
3920

40-
try modules.put("httpz", httpz_module);
41-
try modules.put("pg", pg_module);
42-
try modules.put("datetimez", datetimez_module);
43-
try modules.put("mustache", mustache_module);
44-
45-
// // Expose this as a module that others can import
4621
exe.root_module.addImport("httpz", httpz_module);
4722
exe.root_module.addImport("pg", pg_module);
4823
exe.root_module.addImport("datetimez", datetimez_module);

frameworks/Zig/httpz/src/endpoints.zig

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,16 @@ const pg = @import("pg");
44
const datetimez = @import("datetimez");
55
const mustache = @import("mustache");
66

7-
const Allocator = std.mem.Allocator;
87
const Thread = std.Thread;
98
const Mutex = Thread.Mutex;
109
const template = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{{#fortunes}}<tr><td>{{id}}</td><td>{{message}}</td></tr>{{/fortunes}}</table></body></html>";
1110

1211
pub const Global = struct {
1312
pool: *pg.Pool,
1413
prng: *std.rand.DefaultPrng,
15-
allocator: Allocator,
1614
mutex: std.Thread.Mutex = .{},
1715
};
1816

19-
const Message = struct {
20-
message: []const u8,
21-
};
22-
2317
const World = struct {
2418
id: i32,
2519
randomNumber: i32,
@@ -30,23 +24,21 @@ const Fortune = struct {
3024
message: []const u8,
3125
};
3226

33-
pub fn plaintext(global: *Global, _: *httpz.Request, res: *httpz.Response) !void {
34-
try setHeaders(global.allocator, res);
27+
pub fn plaintext(_: *Global, _: *httpz.Request, res: *httpz.Response) !void {
28+
try setHeaders(res.arena, res);
3529

3630
res.content_type = .TEXT;
3731
res.body = "Hello, World!";
3832
}
3933

40-
pub fn json(global: *Global, _: *httpz.Request, res: *httpz.Response) !void {
41-
try setHeaders(global.allocator, res);
34+
pub fn json(_: *Global, _: *httpz.Request, res: *httpz.Response) !void {
35+
try setHeaders(res.arena, res);
4236

43-
const message = Message{ .message = "Hello, World!" };
44-
45-
try res.json(message, .{});
37+
try res.json(.{ .message = "Hello, World!" }, .{});
4638
}
4739

4840
pub fn db(global: *Global, _: *httpz.Request, res: *httpz.Response) !void {
49-
try setHeaders(global.allocator, res);
41+
try setHeaders(res.arena, res);
5042

5143
global.mutex.lock();
5244
const random_number = 1 + (global.prng.random().uintAtMost(u32, 9999));
@@ -61,15 +53,15 @@ pub fn db(global: *Global, _: *httpz.Request, res: *httpz.Response) !void {
6153
}
6254

6355
pub fn fortune(global: *Global, _: *httpz.Request, res: *httpz.Response) !void {
64-
try setHeaders(global.allocator, res);
56+
try setHeaders(res.arena, res);
6557

66-
const fortunes_html = try getFortunesHtml(global.allocator, global.pool);
58+
const fortunes_html = try getFortunesHtml(res.arena, global.pool);
6759

6860
res.header("content-type", "text/html; charset=utf-8");
6961
res.body = fortunes_html;
7062
}
7163

72-
fn getWorld(pool: *pg.Pool, random_number: u32) !World{
64+
fn getWorld(pool: *pg.Pool, random_number: u32) !World {
7365
var conn = try pool.acquire();
7466
defer conn.release();
7567

@@ -81,7 +73,7 @@ fn getWorld(pool: *pg.Pool, random_number: u32) !World{
8173
return World{ .id = row.get(i32, 0), .randomNumber = row.get(i32, 1) };
8274
}
8375

84-
fn setHeaders(allocator: Allocator, res: *httpz.Response) !void {
76+
fn setHeaders(allocator: std.mem.Allocator, res: *httpz.Response) !void {
8577
res.header("Server", "Httpz");
8678

8779
const now = datetimez.datetime.Date.now();
@@ -97,10 +89,10 @@ fn setHeaders(allocator: Allocator, res: *httpz.Response) !void {
9789
res.header("Date", now_str);
9890
}
9991

100-
fn getFortunesHtml(allocator: Allocator, pool: *pg.Pool) ![]const u8 {
92+
fn getFortunesHtml(allocator: std.mem.Allocator, pool: *pg.Pool) ![]const u8 {
10193
const fortunes = try getFortunes(allocator, pool);
10294

103-
const raw = try mustache.allocRenderText(allocator, template,.{ .fortunes = fortunes });
95+
const raw = try mustache.allocRenderText(allocator, template, .{ .fortunes = fortunes });
10496

10597
// std.debug.print("mustache output {s}\n", .{raw});
10698

@@ -111,7 +103,7 @@ fn getFortunesHtml(allocator: Allocator, pool: *pg.Pool) ![]const u8 {
111103
return html;
112104
}
113105

114-
fn getFortunes(allocator: Allocator, pool: *pg.Pool) ![]const Fortune {
106+
fn getFortunes(allocator: std.mem.Allocator, pool: *pg.Pool) ![]const Fortune {
115107
var conn = try pool.acquire();
116108
defer conn.release();
117109

@@ -139,7 +131,7 @@ fn cmpFortuneByMessage(_: void, a: Fortune, b: Fortune) bool {
139131
return std.mem.order(u8, a.message, b.message).compare(std.math.CompareOperator.lt);
140132
}
141133

142-
fn deescapeHtml(allocator: Allocator, input: []const u8) ![]const u8 {
134+
fn deescapeHtml(allocator: std.mem.Allocator, input: []const u8) ![]const u8 {
143135
var output = std.ArrayList(u8).init(allocator);
144136
defer output.deinit();
145137

@@ -189,4 +181,3 @@ fn deescapeHtml(allocator: Allocator, input: []const u8) ![]const u8 {
189181

190182
return output.toOwnedSlice();
191183
}
192-

frameworks/Zig/httpz/src/main.zig

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ const RndGen = std.rand.DefaultPrng;
1111
const Allocator = std.mem.Allocator;
1212
const Pool = pg.Pool;
1313

14-
var server: httpz.ServerCtx(*endpoints.Global,*endpoints.Global) = undefined;
14+
var server: httpz.ServerCtx(*endpoints.Global, *endpoints.Global) = undefined;
1515

1616
pub fn main() !void {
17+
const cpu_count = try std.Thread.getCpuCount();
1718
var gpa = std.heap.GeneralPurposeAllocator(.{
1819
.thread_safe = true,
1920
}){};
@@ -25,15 +26,20 @@ pub fn main() !void {
2526

2627
var prng = std.rand.DefaultPrng.init(@as(u64, @bitCast(std.time.milliTimestamp())));
2728

28-
var global = endpoints.Global{ .pool = pg_pool, .prng = &prng, .allocator = allocator };
29+
var global = endpoints.Global{
30+
.pool = pg_pool,
31+
.prng = &prng,
32+
};
2933

30-
server = try httpz.ServerApp(*endpoints.Global).init(allocator, .{
31-
.port = 3000, .address = "0.0.0.0", }, &global);
34+
server = try httpz.ServerApp(*endpoints.Global).init(allocator, .{ .port = 3000, .address = "0.0.0.0", .workers = .{
35+
.count = @truncate(cpu_count),
36+
.max_conn = 4096,
37+
}, .thread_pool = .{ .count = @truncate(cpu_count * 2) } }, &global);
3238
defer server.deinit();
3339

3440
// now that our server is up, we register our intent to handle SIGINT
3541
try std.posix.sigaction(std.posix.SIG.INT, &.{
36-
.handler = .{.handler = shutdown},
42+
.handler = .{ .handler = shutdown },
3743
.mask = std.posix.empty_sigset,
3844
.flags = 0,
3945
}, null);
@@ -50,22 +56,16 @@ pub fn main() !void {
5056
}
5157

5258
fn shutdown(_: c_int) callconv(.C) void {
53-
// this will unblock the server.listen()
5459
server.stop();
5560
}
5661

5762
fn notFound(_: *httpz.Request, res: *httpz.Response) !void {
5863
res.status = 404;
59-
60-
// you can set the body directly to a []u8, but note that the memory
61-
// must be valid beyond your handler. Use the res.arena if you need to allocate
62-
// memory for the body.
6364
res.body = "Not Found";
6465
}
6566

66-
// note that the error handler return `void` and not `!void`
6767
fn errorHandler(req: *httpz.Request, res: *httpz.Response, err: anyerror) void {
6868
res.status = 500;
6969
res.body = "Internal Server Error";
70-
std.log.warn("httpz: unhandled exception for request: {s}\nErr: {}", .{req.url.raw, err});
71-
}
70+
std.log.warn("httpz: unhandled exception for request: {s}\nErr: {}", .{ req.url.raw, err });
71+
}

0 commit comments

Comments
 (0)