Skip to content

Commit

Permalink
zig fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
karlseguin committed Sep 4, 2024
1 parent 906be7e commit 40d05e7
Show file tree
Hide file tree
Showing 13 changed files with 109 additions and 117 deletions.
2 changes: 1 addition & 1 deletion examples/01_basic.zig
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ fn formPost(req: *httpz.Request, res: *httpz.Response) !void {

const w = res.writer();
while (it.next()) |kv| {
try std.fmt.format(w, "{s}={s}\n", .{kv.key, kv.value});
try std.fmt.format(w, "{s}={s}\n", .{ kv.key, kv.value });
}
}

Expand Down
11 changes: 5 additions & 6 deletions examples/02_handler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ const PORT = 8802;
// handlers.

pub fn main() !void {

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();

// We specify our "Handler" and, as the last parameter to init, pass an
// instance of it.
var handler = Handler{};
var server = try httpz.Server(*Handler).init(allocator, .{.port = PORT}, &handler);
var server = try httpz.Server(*Handler).init(allocator, .{ .port = PORT }, &handler);
defer server.deinit();

var router = server.router(.{});
Expand All @@ -41,15 +40,15 @@ const Handler = struct {
// when a request is made and no route matches.
pub fn notFound(_: *Handler, _: *httpz.Request, res: *httpz.Response) !void {
res.status = 404;
res.body = "NOPE!";
res.body = "NOPE!";
}

// If the handler defines the special "uncaughtError" function, it'll be
// called when an action returns an error.
// Note that this function takes an additional parameter (the error) and
// returns a `void` rather than a `!void`.
pub fn uncaughtError(_: *Handler, req: *httpz.Request, res: *httpz.Response, err: anyerror) void {
std.debug.print("uncaught http error at {s}: {}\n", .{req.url.path, err});
std.debug.print("uncaught http error at {s}: {}\n", .{ req.url.path, err });

// Alternative to res.content_type = .TYPE
// useful for dynamic content types, or content types not defined in
Expand Down Expand Up @@ -80,9 +79,9 @@ pub fn hits(h: *Handler, _: *httpz.Request, res: *httpz.Response) !void {

// @atomicRmw returns the previous version so we need to +1 it
// to display the count includin this hit
return res.json(.{.hits = count + 1}, .{});
return res.json(.{ .hits = count + 1 }, .{});
}

fn @"error"(_: *Handler, _: *httpz.Request, _: *httpz.Response) !void {
fn @"error"(_: *Handler, _: *httpz.Request, _: *httpz.Response) !void {
return error.ActionError;
}
4 changes: 2 additions & 2 deletions examples/03_dispatch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn main() !void {
const allocator = gpa.allocator();

var handler = Handler{};
var server = try httpz.Server(*Handler).init(allocator, .{.port = PORT}, &handler);
var server = try httpz.Server(*Handler).init(allocator, .{ .port = PORT }, &handler);
defer server.deinit();

var router = server.router(.{});
Expand All @@ -37,7 +37,7 @@ const Handler = struct {
// we could do authentication and set the response directly on error.
try action(self, req, res);

std.debug.print("ts={d} us={d} path={s}\n", .{std.time.timestamp(), start.lap() / 1000, req.url.path});
std.debug.print("ts={d} us={d} path={s}\n", .{ std.time.timestamp(), start.lap() / 1000, req.url.path });
}
};

Expand Down
10 changes: 5 additions & 5 deletions examples/04_action_context.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ pub fn main() !void {
const allocator = gpa.allocator();

var handler = Handler{};
var server = try httpz.Server(*Handler).init(allocator, .{.port = PORT}, &handler);
var server = try httpz.Server(*Handler).init(allocator, .{ .port = PORT }, &handler);
defer server.deinit();

var router = server.router(.{});

const restricted_route = &RouteData{.restricted = true};
const restricted_route = &RouteData{ .restricted = true };

// We can register arbitrary data to a route, which we can retrieve
// via req.route_data. This is stored as a `*const anyopaque`.
router.get("/", index, .{});
router.get("/admin", admin, .{.data = restricted_route});
router.get("/admin", admin, .{ .data = restricted_route });

std.debug.print("listening http://localhost:{d}/\n", .{PORT});

Expand Down Expand Up @@ -62,11 +62,11 @@ const Handler = struct {
}
};

const RouteData = struct{
const RouteData = struct {
restricted: bool,
};

const Env = struct{
const Env = struct {
handler: *Handler,
user: ?[]const u8,
};
Expand Down
2 changes: 1 addition & 1 deletion examples/05_request_takeover.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn main() !void {
const allocator = gpa.allocator();

var handler = Handler{};
var server = try httpz.Server(*Handler).init(allocator, .{.port = PORT}, &handler);
var server = try httpz.Server(*Handler).init(allocator, .{ .port = PORT }, &handler);
defer server.deinit();

// Routes aren't used in this mode
Expand Down
6 changes: 3 additions & 3 deletions examples/06_middleware.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,20 @@ pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();

var server = try httpz.Server(void).init(allocator, .{.port = PORT}, {});
var server = try httpz.Server(void).init(allocator, .{ .port = PORT }, {});
defer server.deinit();

// creates an instance of the middleware with the given configuration
// see example/middleware/Logger.zig
const logger = try server.middleware(Logger, .{.query = true});
const logger = try server.middleware(Logger, .{ .query = true });

var router = server.router(.{});

// Apply middleware to all routes created from this point on
router.middlewares = &.{logger};

router.get("/", index, .{});
router.get("/other", other, .{.middlewares = &.{}});
router.get("/other", other, .{ .middlewares = &.{} });

std.debug.print("listening http://localhost:{d}/\n", .{PORT});

Expand Down
8 changes: 4 additions & 4 deletions examples/07_advanced_routing.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn main() !void {
.log = false,
};

var server = try httpz.Server(*Handler).init(allocator, .{.port = PORT}, &default_handler);
var server = try httpz.Server(*Handler).init(allocator, .{ .port = PORT }, &default_handler);
defer server.deinit();

var router = server.router(.{});
Expand All @@ -30,11 +30,11 @@ pub fn main() !void {

// We can define a dispatch function per-route. This will be used instead of Handler.dispatch
// But, sadly, every dispatch method must have the same signature (they must all accept the same type of action)
router.get("/page1", page1, .{.dispatcher = Handler.infoDispatch});
router.get("/page1", page1, .{ .dispatcher = Handler.infoDispatch });

// We can define a handler instance per-route. This will be used instead of the
// handler instance passed to the init method above.
router.get("/page2", page2, .{.handler = &nolog_handler});
router.get("/page2", page2, .{ .handler = &nolog_handler });

std.debug.print("listening http://localhost:{d}/\n", .{PORT});

Expand All @@ -53,7 +53,7 @@ const Handler = struct {
pub fn dispatch(h: *Handler, action: httpz.Action(*Handler), req: *httpz.Request, res: *httpz.Response) !void {
try action(h, req, res);
if (h.log) {
std.debug.print("ts={d} path={s} status={d}\n", .{std.time.timestamp(), req.url.path, res.status});
std.debug.print("ts={d} path={s} status={d}\n", .{ std.time.timestamp(), req.url.path, res.status });
}
}
};
Expand Down
12 changes: 5 additions & 7 deletions examples/08_websocket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@ const Allocator = std.mem.Allocator;
const PORT = 8808;

// websocket.zig is verbose, let's limit it to err messages
pub const std_options = .{
.log_scope_levels = &[_]std.log.ScopeLevel{
.{ .scope = .websocket, .level = .err },
}
};
pub const std_options = .{ .log_scope_levels = &[_]std.log.ScopeLevel{
.{ .scope = .websocket, .level = .err },
} };

// This example show how to upgrade a request to websocket.
pub fn main() !void {
Expand All @@ -21,7 +19,7 @@ pub fn main() !void {

// For websocket support, you _must_ define a Handler, and your Handler _must_
// have a WebsocketHandler decleration
var server = try httpz.Server(Handler).init(allocator, .{.port = PORT}, Handler{});
var server = try httpz.Server(Handler).init(allocator, .{ .port = PORT }, Handler{});
defer server.deinit();

var router = server.router(.{});
Expand Down Expand Up @@ -86,7 +84,7 @@ fn index(_: Handler, _: *httpz.Request, res: *httpz.Response) !void {
fn ws(_: Handler, req: *httpz.Request, res: *httpz.Response) !void {
// Could do authentication or anything else before upgrading the connection
// The context is any arbitrary data you want to pass to Client.init.
const ctx = Client.Context{.user_id = 9001};
const ctx = Client.Context{ .user_id = 9001 };

// The first parameter, Client, ***MUST*** be the same as Handler.WebSocketHandler
// I'm sorry about the awkwardness of that.
Expand Down
19 changes: 8 additions & 11 deletions src/httpz.zig
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ pub fn Server(comptime H: type) type {
const Handler = switch (@typeInfo(H)) {
.@"struct" => H,
.pointer => |ptr| ptr.child,
.@"void" => void,
.void => void,
else => @compileError("Server handler must be a struct, got: " ++ @tagName(@typeInfo(H))),
};

Expand Down Expand Up @@ -604,7 +604,7 @@ pub fn Server(comptime H: type) type {

if (index < middlewares.len) {
self.index = index + 1;
return middlewares[index].execute(self.req, self.res, self);
return middlewares[index].execute(self.req, self.res, self);
}

// done executing our middlewares, now we either execute the
Expand Down Expand Up @@ -752,7 +752,7 @@ test "tests:beforeAll" {
const ga = global_test_allocator.allocator();

{
default_server = try Server(void).init(ga, .{.port = 5992}, {});
default_server = try Server(void).init(ga, .{ .port = 5992 }, {});

// only need to do this because we're using listenInNewThread instead
// of blocking here. So the array to hold the middleware needs to outlive
Expand All @@ -766,7 +766,7 @@ test "tests:beforeAll" {
});

var middlewares = try default_server.arena.alloc(Middleware(void), 2);
middlewares[0] = try default_server.middleware(TestMiddleware, .{.id = 100});
middlewares[0] = try default_server.middleware(TestMiddleware, .{ .id = 100 });
middlewares[1] = cors[0];

var router = default_server.router(.{});
Expand All @@ -776,9 +776,9 @@ test "tests:beforeAll" {
router.get("/test/query", TestDummyHandler.reqQuery, .{});
router.get("/test/stream", TestDummyHandler.eventStream, .{});
router.get("/test/chunked", TestDummyHandler.chunked, .{});
router.get("/test/route_data", TestDummyHandler.routeData, .{.data = &TestDummyHandler.RouteData{.power = 12345}});
router.all("/test/cors", TestDummyHandler.jsonRes, .{.middlewares = cors});
router.all("/test/middlewares", TestDummyHandler.middlewares, .{.middlewares = middlewares});
router.get("/test/route_data", TestDummyHandler.routeData, .{ .data = &TestDummyHandler.RouteData{ .power = 12345 } });
router.all("/test/cors", TestDummyHandler.jsonRes, .{ .middlewares = cors });
router.all("/test/middlewares", TestDummyHandler.middlewares, .{ .middlewares = middlewares });
router.all("/test/dispatcher", TestDummyHandler.dispatchedAction, .{ .dispatcher = TestDummyHandler.routeSpecificDispacthcer });
test_server_threads[0] = try default_server.listenInNewThread();
}
Expand Down Expand Up @@ -1092,7 +1092,6 @@ test "httpz: CORS" {
var res = testReadParsed(stream);
defer res.deinit();


try t.expectEqual(null, res.headers.get("Access-Control-Max-Age"));
try t.expectEqual(null, res.headers.get("Access-Control-Allow-Methods"));
try t.expectEqual(null, res.headers.get("Access-Control-Allow-Headers"));
Expand Down Expand Up @@ -1476,7 +1475,6 @@ const TestDummyHandler = struct {
return res.directWriter().writeAll("action");
}


fn middlewares(req: *Request, res: *Response) !void {
return res.json(.{
.v1 = TestMiddleware.value1(req),
Expand Down Expand Up @@ -1641,7 +1639,6 @@ const TestWebsocketHandler = struct {
}
};


const TestMiddleware = struct {
const Config = struct {
id: i32,
Expand All @@ -1659,7 +1656,7 @@ const TestMiddleware = struct {
};
}

pub fn deinit(self: *const TestMiddleware)void {
pub fn deinit(self: *const TestMiddleware) void {
self.allocator.free(self.v2);
}

Expand Down
4 changes: 1 addition & 3 deletions src/request.zig
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,7 @@ pub const Request = struct {
return self.fd;
}

fn parseMultiFormData(
self: *Request,
) !*MultiFormKeyValue {
fn parseMultiFormData(self: *Request) !*MultiFormKeyValue {
const body_ = self.body() orelse "";
if (body_.len == 0) {
self.fd_read = true;
Expand Down
16 changes: 8 additions & 8 deletions src/response.zig
Original file line number Diff line number Diff line change
Expand Up @@ -191,19 +191,19 @@ pub const Response = struct {
const names = headers.keys[0..headers.len];
const values = headers.values[0..headers.len];

var len: usize = 0;
// 200 gives us enough space to fit:
// 1 - The status/first line
// 2 - The Content-Length header or the Transfer-Encoding header.
// 3 - Our longest supported built-in content type (for a custom content
// type, it would have been set via the res.header(...) call, so would
// be included in `len)
var len: usize = 200;
for (names, values) |name, value| {
// +4 for the colon, space and trailer
len += name.len + value.len + 4;
}

// +200 gives us enough space to fit:
// The status/first line
// Our longest supported built-in content type (for a custom content
// type, it would have been set via the res.header(...) call, so would
// be included in `len)
// The Content-Length header or the Transfer-Encoding header.
var buf = try self.arena.alloc(u8, len + 200);
var buf = try self.arena.alloc(u8, len);

var pos: usize = "HTTP/1.1 XXX \r\n".len;
switch (self.status) {
Expand Down
Loading

0 comments on commit 40d05e7

Please sign in to comment.