Merge pull request #199 from jetzig-framework/public-routing-path

Public routing path
This commit is contained in:
bobf 2025-05-05 10:44:07 +01:00 committed by GitHub
commit acacd209bd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 17 additions and 2 deletions

View File

@ -66,6 +66,10 @@ pub const jetzig_options = struct {
// Path relative to cwd() to serve public content from. Symlinks are not followed.
pub const public_content_path = "public";
/// Request path to map to public directory, e.g. if `public_routing_path` is `"/foo"` then a
/// request to `/foo/bar.png` will serve static content found in `public/bar.png`
pub const public_routing_path = "/";
// HTTP buffer. Must be large enough to store all headers. This should typically not be modified.
pub const http_buffer_size: usize = std.math.pow(usize, 2, 16);

View File

@ -84,6 +84,10 @@ pub const max_connections: u16 = 512;
/// Path relative to cwd() to serve public content from. Symlinks are not followed.
pub const public_content_path = "public";
/// Request path to map to public directory, e.g. if `public_routing_path` is `"/foo"` then a
/// request to `/foo/bar.png` will serve static content found in `public/bar.png`
pub const public_routing_path = "/";
/// Middleware chain. Add any custom middleware here, or use middleware provided in
/// `jetzig.middleware` (e.g. `jetzig.middleware.HtmxMiddleware`).
pub const middleware = &.{};

View File

@ -754,9 +754,16 @@ fn matchStaticResource(self: *Server, request: *jetzig.http.Request) !?StaticRes
}
fn matchPublicContent(self: *Server, request: *jetzig.http.Request) !?StaticResource {
if (request.path.file_path.len <= 1) return null;
const public_routing_path = comptime jetzig.config.get([]const u8, "public_routing_path");
if (!std.mem.startsWith(u8, request.path.file_path, public_routing_path)) return null;
if (request.method != .GET) return null;
const match_path = if (comptime std.mem.endsWith(u8, public_routing_path, "/"))
request.path.file_path[public_routing_path.len..]
else if (request.path.file_path.len <= public_routing_path.len + 1) {
return null;
} else request.path.file_path[public_routing_path.len + 1 ..];
var iterable_dir = std.fs.cwd().openDir(
jetzig.config.get([]const u8, "public_content_path"),
.{ .iterate = true, .no_follow = true },
@ -777,7 +784,7 @@ fn matchPublicContent(self: *Server, request: *jetzig.http.Request) !?StaticReso
_ = std.mem.replace(u8, file.path, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix, &path_buffer);
break :blk path_buffer[0..file.path.len];
} else file.path;
if (std.mem.eql(u8, file_path, request.path.file_path[1..])) {
if (std.mem.eql(u8, file_path, match_path)) {
const content = try iterable_dir.readFileAlloc(
request.allocator,
file_path,