Skip to content

Commit

Permalink
Allow responding to HTML when no template present
Browse files Browse the repository at this point in the history
If no template present, allow the request to render the view and then
only render a 404 if the view does not redirect, otherwise all views
would need a placeholder Zmpl template even if the view does not use it.

Also parse HTTP body as query string if present.
  • Loading branch information
bobf committed Apr 2, 2024
1 parent b94845a commit eed58ed
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
3 changes: 2 additions & 1 deletion src/jetzig/http/Request.zig
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ fn queryParams(self: *Self) !*jetzig.data.Value {
}

fn parseQueryString(self: *Self) !bool {
if (self.path.query) |query| {
const data: ?[]const u8 = if (self.body.len > 0) self.body else self.path.query;
if (data) |query| {
self.query.* = jetzig.http.Query.init(
self.allocator,
query,
Expand Down
24 changes: 16 additions & 8 deletions src/jetzig/http/Server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,18 @@ fn renderHTML(
route: ?*jetzig.views.Route,
) !void {
if (route) |matched_route| {
if (zmpl.find(matched_route.template)) |template| {
const rendered = self.renderView(matched_route, request, template) catch |err| {
if (isUnhandledError(err)) return err;
const rendered_error = try self.renderInternalServerError(request, err);
return request.setResponse(rendered_error, .{});
};
const template = zmpl.find(matched_route.template);
if (template == null) {
if (try self.renderMarkdown(request, route)) |rendered_markdown| {
return request.setResponse(rendered_markdown, .{});
}
}
const rendered = self.renderView(matched_route, request, template) catch |err| {
if (isUnhandledError(err)) return err;
const rendered_error = try self.renderInternalServerError(request, err);
return request.setResponse(rendered_error, .{});
};
if (request.status_code != .not_found) {
return request.setResponse(rendered, .{});
}
}
Expand Down Expand Up @@ -265,8 +271,10 @@ fn renderView(
.content = try self.renderTemplateWithLayout(request, capture, rendered_view, route),
};
} else {
// We are rendering JSON, content is the result of `toJson` on view data.
return .{ .view = rendered_view, .content = "" };
return switch (request.requestFormat()) {
.HTML, .UNKNOWN => try renderNotFound(request),
.JSON => .{ .view = rendered_view, .content = "" },
};
}
} else {
try self.logger.WARN("`request.render` was not invoked. Rendering empty content.", .{});
Expand Down

0 comments on commit eed58ed

Please sign in to comment.