add impl for file fetch

This commit is contained in:
Luna 2021-04-09 18:33:21 -03:00
parent 48da2945d8
commit 43abed7e80
1 changed files with 17 additions and 2 deletions

View File

@ -21,7 +21,7 @@ pub fn main() anyerror!void {
comptime http.router.router(&[_]http.router.Route{
http.router.get("/", index),
http.router.post("/api/upload", uploadFile),
http.router.post("/:filename", fetchFile),
http.router.get("/i/:filename", fetchFile),
}),
);
}
@ -67,6 +67,21 @@ fn uploadFile(response: *http.Response, request: http.Request) !void {
fn fetchFile(response: *http.Response, request: http.Request, filename: []const u8) !void {
std.log.info("got name: {s}", .{filename});
var image_path_buffer: [512]u8 = undefined;
const images_dir = try std.fs.cwd().openDir(images_dir_path, .{});
try response.writer().writeAll("Hello Zig! fetch");
const image_path = try std.fmt.bufPrint(
&image_path_buffer,
"{s}/{s}",
.{ images_dir_path, filename },
);
// TODO return 404 on error
const image_file = try std.fs.cwd().openFile(image_path, .{ .read = false });
while (true) {
var file_write_buffer: [1024]u8 = undefined;
const bytes_read = try image_file.read(&file_write_buffer);
if (bytes_read == 0) return;
try response.writer().writeAll(&file_write_buffer);
}
}