add image uploads
This commit is contained in:
parent
866fee1502
commit
48da2945d8
2 changed files with 56 additions and 2 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,3 +1,4 @@
|
|||
zig-cache/
|
||||
deps.zig
|
||||
images/
|
||||
.zigmod/
|
||||
|
|
57
src/main.zig
57
src/main.zig
|
@ -1,19 +1,72 @@
|
|||
const std = @import("std");
|
||||
const http = @import("apple_pie");
|
||||
|
||||
const images_dir_path = "./images";
|
||||
|
||||
pub fn main() anyerror!void {
|
||||
std.log.info("All your codebase are belong to us.", .{});
|
||||
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
|
||||
const bind_addr = try std.net.Address.parseIp("0.0.0.0", 8080);
|
||||
std.log.info("serving on {}", .{bind_addr});
|
||||
|
||||
// TODO: configurable path via env var
|
||||
try std.fs.cwd().makePath(images_dir_path);
|
||||
|
||||
try http.listenAndServe(
|
||||
&gpa.allocator,
|
||||
try std.net.Address.parseIp("127.0.0.1", 8080),
|
||||
index,
|
||||
bind_addr,
|
||||
comptime http.router.router(&[_]http.router.Route{
|
||||
http.router.get("/", index),
|
||||
http.router.post("/api/upload", uploadFile),
|
||||
http.router.post("/:filename", fetchFile),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
fn index(response: *http.Response, request: http.Request) !void {
|
||||
try response.writer().writeAll("Hello Zig!");
|
||||
}
|
||||
|
||||
fn generateImageId(buffer: []u8) []const u8 {
|
||||
var i: usize = 0;
|
||||
|
||||
const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp()));
|
||||
var r = std.rand.DefaultPrng.init(seed);
|
||||
|
||||
while (i < 16) : (i += 1) {
|
||||
// random ascii lowercase char
|
||||
var idx = @intCast(u8, r.random.uintLessThan(u5, 24));
|
||||
var letter = @as(u8, 97) + idx;
|
||||
buffer[i] = letter;
|
||||
}
|
||||
|
||||
return buffer[0..i];
|
||||
}
|
||||
|
||||
fn uploadFile(response: *http.Response, request: http.Request) !void {
|
||||
std.log.info("upload! got {d} bytes", .{request.body.len});
|
||||
|
||||
var image_id_buffer: [256]u8 = undefined;
|
||||
const image_id = generateImageId(&image_id_buffer);
|
||||
|
||||
var image_path_buffer: [512]u8 = undefined;
|
||||
const image_path = try std.fmt.bufPrint(
|
||||
&image_path_buffer,
|
||||
"{s}/{s}.jpg",
|
||||
.{ images_dir_path, image_id },
|
||||
);
|
||||
|
||||
const image_file = try std.fs.cwd().createFile(image_path, .{});
|
||||
try image_file.writer().writeAll(request.body);
|
||||
|
||||
try response.writer().writeAll(image_path);
|
||||
}
|
||||
|
||||
fn fetchFile(response: *http.Response, request: http.Request, filename: []const u8) !void {
|
||||
std.log.info("got name: {s}", .{filename});
|
||||
const images_dir = try std.fs.cwd().openDir(images_dir_path, .{});
|
||||
try response.writer().writeAll("Hello Zig! fetch");
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue