mirror of
https://github.com/jetzig-framework/jetzig.git
synced 2025-05-14 22:16:08 +00:00
Refactoring
This commit is contained in:
parent
f538b0ddce
commit
7339641401
@ -82,7 +82,7 @@ fn isPath(dir: std.fs.Dir, sub_path: []const u8, path_type: enum { file, dir })
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Strip leading and trailing whitespace from a u8 slice.
|
// Strip leading and trailing whitespace from a u8 slice.
|
||||||
pub fn strip(input: []const u8) []const u8 {
|
pub inline fn strip(input: []const u8) []const u8 {
|
||||||
return std.mem.trim(u8, input, &std.ascii.whitespace);
|
return std.mem.trim(u8, input, &std.ascii.whitespace);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -11,14 +11,9 @@ pub const jetzig_options = struct {
|
|||||||
/// Middleware chain. Add any custom middleware here, or use middleware provided in
|
/// Middleware chain. Add any custom middleware here, or use middleware provided in
|
||||||
/// `jetzig.middleware` (e.g. `jetzig.middleware.HtmxMiddleware`).
|
/// `jetzig.middleware` (e.g. `jetzig.middleware.HtmxMiddleware`).
|
||||||
pub const middleware: []const type = &.{
|
pub const middleware: []const type = &.{
|
||||||
// htmx middleware skips layouts when `HX-Target` header is present and issues
|
// jetzig.middleware.HtmxMiddleware,
|
||||||
// `HX-Redirect` instead of a regular HTTP redirect when `request.redirect` is called.
|
// jetzig.middleware.CompressionMiddleware,
|
||||||
jetzig.middleware.HtmxMiddleware,
|
// @import("app/middleware/DemoMiddleware.zig"),
|
||||||
// Compression middleware compresses every request to decrease transfer size
|
|
||||||
jetzig.middleware.CompressionMiddleware,
|
|
||||||
// Demo middleware included with new projects. Remove once you are familiar with Jetzig's
|
|
||||||
// middleware system.
|
|
||||||
@import("app/middleware/DemoMiddleware.zig"),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Maximum bytes to allow in request body.
|
// Maximum bytes to allow in request body.
|
||||||
|
@ -398,10 +398,7 @@ fn isBadHttpError(err: anyerror) bool {
|
|||||||
fn renderInternalServerError(self: *Server, request: *jetzig.http.Request, err: anyerror) !RenderedView {
|
fn renderInternalServerError(self: *Server, request: *jetzig.http.Request, err: anyerror) !RenderedView {
|
||||||
request.response_data.reset();
|
request.response_data.reset();
|
||||||
|
|
||||||
try self.logger.ERROR("Encountered Error: {s}", .{@errorName(err)});
|
try self.logger.logError(err);
|
||||||
|
|
||||||
const stack = @errorReturnTrace();
|
|
||||||
if (stack) |capture| try self.logStackTrace(capture, .{ .jetzig = request });
|
|
||||||
|
|
||||||
const status = .internal_server_error;
|
const status = .internal_server_error;
|
||||||
return try self.renderError(request, status);
|
return try self.renderError(request, status);
|
||||||
@ -444,12 +441,7 @@ fn renderErrorView(
|
|||||||
|
|
||||||
_ = route.render(route.*, request) catch |err| {
|
_ = route.render(route.*, request) catch |err| {
|
||||||
if (isUnhandledError(err)) return err;
|
if (isUnhandledError(err)) return err;
|
||||||
try self.logger.ERROR(
|
try self.logger.logError(err);
|
||||||
"Unexepected error occurred while rendering error page: {s}",
|
|
||||||
.{@errorName(err)},
|
|
||||||
);
|
|
||||||
const stack = @errorReturnTrace();
|
|
||||||
if (stack) |capture| try self.logStackTrace(capture, .{ .jetzig = request });
|
|
||||||
return try renderDefaultError(request, status_code);
|
return try renderDefaultError(request, status_code);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -70,6 +70,12 @@ pub const Logger = union(enum) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn logError(self: *const Logger, err: anyerror) !void {
|
||||||
|
switch (self.*) {
|
||||||
|
inline else => |*logger| try logger.logError(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn log(
|
pub fn log(
|
||||||
self: *const Logger,
|
self: *const Logger,
|
||||||
comptime level: LogLevel,
|
comptime level: LogLevel,
|
||||||
|
@ -104,6 +104,19 @@ pub fn logRequest(self: DevelopmentLogger, request: *const jetzig.http.Request)
|
|||||||
}, .stdout);
|
}, .stdout);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn logError(self: *const DevelopmentLogger, err: anyerror) !void {
|
||||||
|
if (@errorReturnTrace()) |stack| {
|
||||||
|
try self.log(.ERROR, "\nStack Trace:\n{}", .{stack});
|
||||||
|
var buf = std.ArrayList(u8).init(self.allocator);
|
||||||
|
defer buf.deinit();
|
||||||
|
const writer = buf.writer();
|
||||||
|
try stack.format("", .{}, writer);
|
||||||
|
try self.logger.ERROR("{s}\n", .{buf.items});
|
||||||
|
}
|
||||||
|
|
||||||
|
try self.log(.ERROR, "Encountered Error: {s}", .{@errorName(err)});
|
||||||
|
}
|
||||||
|
|
||||||
inline fn colorizedLogLevel(comptime level: LogLevel) []const u8 {
|
inline fn colorizedLogLevel(comptime level: LogLevel) []const u8 {
|
||||||
return switch (level) {
|
return switch (level) {
|
||||||
.TRACE => jetzig.colors.white(@tagName(level)),
|
.TRACE => jetzig.colors.white(@tagName(level)),
|
||||||
|
@ -101,6 +101,10 @@ pub fn logRequest(self: *const JsonLogger, request: *const jetzig.http.Request)
|
|||||||
try self.log_queue.print("{s}\n", .{stream.getWritten()}, .stdout);
|
try self.log_queue.print("{s}\n", .{stream.getWritten()}, .stdout);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn logError(self: *const JsonLogger, err: anyerror) !void {
|
||||||
|
try self.log(.ERROR, "Encountered error: {s}", .{@errorName(err)});
|
||||||
|
}
|
||||||
|
|
||||||
fn getFile(self: JsonLogger, level: LogLevel) std.fs.File {
|
fn getFile(self: JsonLogger, level: LogLevel) std.fs.File {
|
||||||
return switch (level) {
|
return switch (level) {
|
||||||
.TRACE, .DEBUG, .INFO => self.stdout,
|
.TRACE, .DEBUG, .INFO => self.stdout,
|
||||||
|
@ -1,72 +1,59 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const jetzig = @import("jetzig");
|
const jetzig = @import("../../jetzig.zig");
|
||||||
|
|
||||||
|
fn isCompressable(content_type: []const u8) bool {
|
||||||
|
const type_list = .{
|
||||||
|
"text/html",
|
||||||
|
"application/xhtml+xml",
|
||||||
|
"application/xml",
|
||||||
|
"text/css",
|
||||||
|
"text/javascript",
|
||||||
|
"application/json",
|
||||||
|
"application/pdf",
|
||||||
|
"image/svg+xml",
|
||||||
|
};
|
||||||
|
|
||||||
fn checkType(content_type: []const u8) bool {
|
|
||||||
const type_list = .{ "text/html", "application/xhtml+xml", "application/xml", "text/css", "text/javascript", "application/json", "application/pdf", "image/svg+xml" };
|
|
||||||
inline for (type_list) |content| {
|
inline for (type_list) |content| {
|
||||||
if (std.mem.eql(u8, content_type, content)) return true;
|
if (std.mem.eql(u8, content_type, content)) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Encoding = enum {
|
const Encoding = enum { gzip, deflate };
|
||||||
None,
|
|
||||||
Gzip,
|
|
||||||
Deflate,
|
|
||||||
};
|
|
||||||
const err_msg = "Response was not compressed due to error: {s}";
|
|
||||||
/// Parse accepted encoding, encode responses if possible, set appropriate headers, and
|
/// Parse accepted encoding, encode responses if possible, set appropriate headers, and
|
||||||
/// modify the response accordingly to decrease response size
|
/// modify the response accordingly to decrease response size
|
||||||
pub fn beforeResponse(request: *jetzig.http.Request, response: *jetzig.http.Response) !void {
|
pub fn beforeResponse(request: *jetzig.http.Request, response: *jetzig.http.Response) !void {
|
||||||
// Only some file types need compressions, skip the others
|
if (!isCompressable(response.content_type)) return;
|
||||||
if (!checkType(response.content_type)) return;
|
const encoding = detectEncoding(request) orelse return;
|
||||||
|
|
||||||
// Find matching encoding
|
const compressed = switch (encoding) {
|
||||||
var encoding = Encoding.None;
|
.gzip => jetzig.util.gzip(request.allocator, response.content, .{}) catch |err|
|
||||||
for (request.headers.getAll("Accept-Encoding")) |encodings| find_encoding: {
|
return request.server.logger.logError(err),
|
||||||
var buffer: [64]u8 = undefined;
|
.deflate => jetzig.util.deflate(request.allocator, response.content, .{}) catch |err|
|
||||||
var encodings_stream = std.io.fixedBufferStream(encodings);
|
return request.server.logger.logError(err),
|
||||||
var encodings_reader = encodings_stream.reader();
|
};
|
||||||
while (try encodings_reader.readUntilDelimiterOrEof(&buffer, ',')) |encoding_str| {
|
|
||||||
const encoding_trimmed = encoding_str[if (encoding_str[0] == ' ') 1 else 0..];
|
response.headers.append("Content-Encoding", @tagName(encoding)) catch |err|
|
||||||
const encoding_list = .{ "gzip", "deflate" };
|
return request.server.logger.logError(err);
|
||||||
inline for (encoding_list, 0..) |encoding_compare, i| {
|
|
||||||
if (std.mem.eql(u8, encoding_compare, encoding_trimmed)) {
|
|
||||||
encoding = @enumFromInt(i + 1);
|
|
||||||
break :find_encoding;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
std.debug.print("Encoding: {s}\n", .{encoding_str});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (encoding == .None) return;
|
|
||||||
|
|
||||||
// Compress data
|
|
||||||
var compressed = std.ArrayList(u8).init(request.allocator);
|
|
||||||
var content_reader = std.io.fixedBufferStream(response.content);
|
|
||||||
switch (encoding) {
|
|
||||||
.Gzip => {
|
|
||||||
std.compress.gzip.compress(content_reader.reader(), compressed.writer(), .{ .level = .fast }) catch |err|
|
|
||||||
return request.server.logger.ERROR(err_msg, .{@errorName(err)});
|
|
||||||
response.headers.append("Content-Encoding", "gzip") catch |err|
|
|
||||||
return request.server.logger.ERROR(err_msg, .{@errorName(err)});
|
|
||||||
},
|
|
||||||
.Deflate => {
|
|
||||||
std.compress.flate.compress(content_reader.reader(), compressed.writer(), .{ .level = .fast }) catch |err|
|
|
||||||
return request.server.logger.ERROR(err_msg, .{@errorName(err)});
|
|
||||||
response.headers.append("Content-Encoding", "deflate") catch |err|
|
|
||||||
return request.server.logger.ERROR(err_msg, .{@errorName(err)});
|
|
||||||
},
|
|
||||||
else => {
|
|
||||||
// The compression is not supported
|
|
||||||
// TODO: Can add zstd and br in the future, but gzip / deflate
|
|
||||||
// support through the std is good enough
|
|
||||||
return;
|
|
||||||
},
|
|
||||||
}
|
|
||||||
// Make caching work
|
// Make caching work
|
||||||
response.headers.append("Vary", "Accept-Encoding") catch |err|
|
response.headers.append("Vary", "Accept-Encoding") catch |err|
|
||||||
return request.server.logger.ERROR(err_msg, .{@errorName(err)});
|
return request.server.logger.logError(err);
|
||||||
|
|
||||||
response.content = compressed.items;
|
response.content = compressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detectEncoding(request: *const jetzig.http.Request) ?Encoding {
|
||||||
|
for (request.headers.getAll("Accept-Encoding")) |encodings| {
|
||||||
|
var it = std.mem.tokenizeScalar(u8, encodings, ',');
|
||||||
|
while (it.next()) |param| {
|
||||||
|
inline for (@typeInfo(Encoding).Enum.fields) |field| {
|
||||||
|
if (std.mem.eql(u8, field.name, jetzig.util.strip(param))) {
|
||||||
|
return std.enums.nameCast(Encoding, field.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -33,6 +33,27 @@ pub fn base64Decode(allocator: std.mem.Allocator, string: []const u8) ![]u8 {
|
|||||||
return ptr;
|
return ptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn gzip(allocator: std.mem.Allocator, content: []const u8, options: struct {}) ![]const u8 {
|
||||||
|
_ = options; // Allow setting compression options later if needed.
|
||||||
|
var compressed = std.ArrayList(u8).init(allocator);
|
||||||
|
var content_reader = std.io.fixedBufferStream(content);
|
||||||
|
try std.compress.gzip.compress(content_reader.reader(), compressed.writer(), .{ .level = .fast });
|
||||||
|
return try compressed.toOwnedSlice();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deflate(allocator: std.mem.Allocator, content: []const u8, options: struct {}) ![]const u8 {
|
||||||
|
_ = options; // Allow setting compression options later if needed.
|
||||||
|
var compressed = std.ArrayList(u8).init(allocator);
|
||||||
|
var content_reader = std.io.fixedBufferStream(content);
|
||||||
|
try std.compress.flate.compress(content_reader.reader(), compressed.writer(), .{ .level = .fast });
|
||||||
|
return try compressed.toOwnedSlice();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip leading and trailing whitespace from a u8 slice.
|
||||||
|
pub inline fn strip(input: []const u8) []const u8 {
|
||||||
|
return std.mem.trim(u8, input, &std.ascii.whitespace);
|
||||||
|
}
|
||||||
|
|
||||||
/// Generate a secure random string of `len` characters (for cryptographic purposes).
|
/// Generate a secure random string of `len` characters (for cryptographic purposes).
|
||||||
pub fn generateSecret(allocator: std.mem.Allocator, comptime len: u10) ![]const u8 {
|
pub fn generateSecret(allocator: std.mem.Allocator, comptime len: u10) ![]const u8 {
|
||||||
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||||
|
Loading…
x
Reference in New Issue
Block a user