From 48e30ca35c57c9e3581e0f6277c0369fbdc87035 Mon Sep 17 00:00:00 2001 From: Rene Schallner Date: Fri, 12 May 2023 23:34:12 +0200 Subject: [PATCH] feature: SimpleRequest.sendFile(filename) --- build.zig | 21 ++++++++++++ build.zig.zon | 2 +- src/tests/test_sendfile.zig | 64 +++++++++++++++++++++++++++++++++++++ src/tests/testfile.txt | 1 + src/zap.zig | 16 ++++++++++ 5 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 src/tests/test_sendfile.zig create mode 100644 src/tests/testfile.txt diff --git a/build.zig b/build.zig index 9d30810..5f54516 100644 --- a/build.zig +++ b/build.zig @@ -137,6 +137,23 @@ pub fn build(b: *std.build.Builder) !void { // we can call it again when needed. const install_httpparams_tests = b.addInstallArtifact(httpparams_tests); + // http paramters (qyery, body) tests + const sendfile_tests = b.addTest(.{ + .name = "sendfile_tests", + .root_source_file = .{ .path = "src/tests/test_sendfile.zig" }, + .target = target, + .optimize = optimize, + }); + + sendfile_tests.linkLibrary(facil_dep.artifact("facil.io")); + sendfile_tests.addModule("zap", zap_module); + const run_sendfile_tests = b.addRunArtifact(sendfile_tests); + // TODO: for some reason, tests aren't run more than once unless + // dependencies have changed. + // So, for now, we just force the exe to be built, so in order that + // we can call it again when needed. + const install_sendfile_tests = b.addInstallArtifact(sendfile_tests); + // test commands const run_auth_test_step = b.step("test-authentication", "Run auth unit tests [REMOVE zig-cache!]"); run_auth_test_step.dependOn(&run_auth_tests.step); @@ -146,6 +163,10 @@ pub fn build(b: *std.build.Builder) !void { run_httpparams_test_step.dependOn(&run_httpparams_tests.step); run_httpparams_test_step.dependOn(&install_httpparams_tests.step); + const run_sendfile_test_step = b.step("test-sendfile", "Run http param unit tests [REMOVE zig-cache!]"); + run_sendfile_test_step.dependOn(&run_sendfile_tests.step); + run_sendfile_test_step.dependOn(&install_sendfile_tests.step); + // pkghash // var pkghash_exe = b.addExecutable(.{ diff --git a/build.zig.zon b/build.zig.zon index 58e8647..4837601 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = "zap", - .version = "0.0.18", + .version = "0.0.19", .dependencies = .{ .@"facil.io" = .{ diff --git a/src/tests/test_sendfile.zig b/src/tests/test_sendfile.zig new file mode 100644 index 0000000..2bad45c --- /dev/null +++ b/src/tests/test_sendfile.zig @@ -0,0 +1,64 @@ +const std = @import("std"); +const zap = @import("zap"); + +var buffer: [1024]u8 = undefined; +var read_len: ?usize = null; + +const testfile = @embedFile("testfile.txt"); + +fn makeRequest(a: std.mem.Allocator, url: []const u8) !void { + const uri = try std.Uri.parse(url); + + var h = std.http.Headers{ .allocator = a }; + defer h.deinit(); + + var http_client: std.http.Client = .{ .allocator = a }; + defer http_client.deinit(); + + var req = try http_client.request(.GET, uri, h, .{}); + defer req.deinit(); + + try req.start(); + try req.wait(); + read_len = try req.readAll(&buffer); + + zap.fio_stop(); +} + +fn makeRequestThread(a: std.mem.Allocator, url: []const u8) !std.Thread { + return try std.Thread.spawn(.{}, makeRequest, .{ a, url }); +} +pub fn on_request(r: zap.SimpleRequest) void { + r.sendFile("src/tests/testfile.txt") catch unreachable; +} + +test "send file" { + var allocator = std.testing.allocator; + + // setup listener + var listener = zap.SimpleHttpListener.init( + .{ + .port = 3001, + .on_request = on_request, + .log = false, + .max_clients = 10, + .max_body_size = 1 * 1024, + }, + ); + zap.enableDebugLog(); + try listener.listen(); + + const thread = try makeRequestThread(allocator, "http://127.0.0.1:3001/?file=src/tests/testfile.txt"); + defer thread.join(); + zap.start(.{ + .threads = 1, + .workers = 0, + }); + + if (read_len) |rl| { + try std.testing.expectEqual(testfile.len, rl); + try std.testing.expectEqualSlices(u8, testfile, buffer[0..rl]); + } else { + return error.Wrong; + } +} diff --git a/src/tests/testfile.txt b/src/tests/testfile.txt new file mode 100644 index 0000000..4b5fa63 --- /dev/null +++ b/src/tests/testfile.txt @@ -0,0 +1 @@ +hello, world diff --git a/src/zap.zig b/src/zap.zig index 6f17ccd..96cd5df 100644 --- a/src/zap.zig +++ b/src/zap.zig @@ -52,6 +52,7 @@ pub const HttpError = error{ HttpParseBody, HttpIterParams, SetCookie, + SendFile, }; pub const ContentType = enum { @@ -171,6 +172,21 @@ pub const SimpleRequest = struct { self.h.*.status = @intCast(usize, @enumToInt(status)); } + /// Sends a file if present in the filesystem orelse returns an error. + /// + /// - efficiently sends a file using gzip compression + /// - also handles range requests if `Range` or `If-Range` headers are present in the request. + /// - sends the response headers and the specified file (the response's body). + /// + /// On success, the `self.h` handle will be consumed and invalid. + /// On error, the handle will still be valid and should be used to send an error response + /// + /// Important: sets last-modified and cache-control headers with a max-age value of 1 hour! + pub fn sendFile(self: *const Self, file_path: []const u8) !void { + if (fio.http_sendfile2(self.h, util.toCharPtr(file_path), file_path.len, null, 0) != 0) + return error.SendFile; + } + /// Attempts to decode the request's body. /// This should be called BEFORE parseQuery /// Result is accessible via parametersToOwnedSlice(), parametersToOwnedStrSlice()