diff --git a/src/helpers.zig b/src/helpers.zig index c3f2aa9..2c92d1b 100644 --- a/src/helpers.zig +++ b/src/helpers.zig @@ -365,3 +365,11 @@ pub fn sanitize(allocator: std.mem.Allocator, path: []const u8) ![]u8 { // replace double slash (//) with single slash (/) return buf[0..std.mem.collapseRepeatsLen(u8, buf, '/')]; } + +pub fn try_path(conn: *Connection, dir: std.Io.Dir, path: ?[]const u8) !bool { + sendfile(conn, dir, path orelse conn.path) catch |err| switch (err) { + error.FileNotFound => return false, + else => return err, + }; + return true; +} diff --git a/src/root.zig b/src/root.zig index 702ef33..9662dba 100644 --- a/src/root.zig +++ b/src/root.zig @@ -153,38 +153,21 @@ fn handle_fs(conn: *Connection) !void { const build_dir = try std.Io.Dir.openDirAbsolute(io, config.buildroot, .{}); defer build_dir.close(io); - try_build: { - return helpers.sendfile(conn, build_dir, conn.path) catch |err| switch (err) { - error.FileNotFound => break :try_build, - else => return err, - }; + if (std.mem.eql(u8, conn.path, "/")) { + if (try helpers.try_path(conn, build_dir, "/index.html")) return; + return error.FileNotFound; } - try_build_index_html: { - if (std.mem.eql(u8, conn.path, "/")) { - return helpers.sendfile(conn, build_dir, "/index.html") catch |err| switch (err) { - error.FileNotFound => break :try_build_index_html, - else => return err, - }; - } - - const path = try std.mem.join(allocator, "/", &.{ conn.path, "index.html" }); - defer allocator.free(path); - return helpers.sendfile(conn, build_dir, path) catch |err| switch (err) { - error.FileNotFound => break :try_build_index_html, - else => return err, - }; - } + if (try helpers.try_path(conn, build_dir, null)) return; + + const path = try std.mem.join(allocator, "/", &.{ conn.path, "index.html" }); + defer allocator.free(path); + if (try helpers.try_path(conn, build_dir, path)) return; const static_dir = try std.Io.Dir.openDirAbsolute(io, config.staticroot, .{}); defer static_dir.close(io); - try_static: { - return helpers.sendfile(conn, static_dir, conn.path) catch |err| switch (err) { - error.FileNotFound => break :try_static, - else => return err, - }; - } + if (try helpers.try_path(conn, static_dir, null)) return; return error.FileNotFound; }