Skip to content

Instantly share code, notes, and snippets.

@zigster64
Last active April 24, 2023 15:36
Show Gist options
  • Save zigster64/588fff1a6ae4ea4737dd2782214fa498 to your computer and use it in GitHub Desktop.
Save zigster64/588fff1a6ae4ea4737dd2782214fa498 to your computer and use it in GitHub Desktop.
use std.os.sendfile with zig std.http.server
fn sendfile(res: *std.http.Server.Response, filename: []const u8) !void {
var file = std.fs.cwd().openFile(filename, .{}) catch {
// TODO - Add any extra 404 handling code here
res.status = .not_found;
try res.do();
return;
};
defer file.close();
const file_len = try file.getEndPos();
res.transfer_encoding = .{ .content_length = file_len };
try res.do();
const zero_iovec = &[0]std.os.iovec_const{};
var send_total: usize = 0;
while (true) {
const send_len = try std.os.sendfile(
res.connection.conn.stream.handle,
file.handle,
send_total,
file_len,
zero_iovec, zero_iovec, 0);
if (send_len == 0)
break;
send_total += send_len;
}
}
// Example Usage from a handler function
fn handler(res: *Server.Response) !void {
while (true) {
defer res.reset();
try res.wait();
switch (res.request.method) {
.GET => {
// TODO - sanity check that they are asking for a file here
// TODO - validate the file / 404 check / check if its a file or dir or whatever ...
try sendfile(res, res.request.target[1..]);
},
else => {
// do the thing
},
}
if (res.connection.conn.closing) break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment