Proof of concept
This commit is contained in:
66
packages/myid/src/http.zig
Normal file
66
packages/myid/src/http.zig
Normal file
@@ -0,0 +1,66 @@
|
||||
const std = @import("std");
|
||||
const main = @import("main.zig");
|
||||
|
||||
threadlocal var read_buffer: [2 * 1024 * 1024]u8 = undefined;
|
||||
threadlocal var write_buffer: [2 * 1024 * 1024]u8 = undefined;
|
||||
|
||||
const http_400 = "HTTP/1.1 400 Bad Request\r\n\r\n";
|
||||
const http_404 = "HTTP/1.1 404 Not Found\r\n\r\n";
|
||||
const http_413 = "HTTP/1.1 413 Content Too Large\r\n\r\n";
|
||||
const http_431 = "HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n";
|
||||
const http_500 = "HTTP/1.1 500 Internal Server Error\r\n\r\n";
|
||||
|
||||
const log = std.log.scoped(.http);
|
||||
|
||||
fn http_200(content_type: []const u8, response_body: []const u8) ![]const u8 {
|
||||
var fbs = std.io.fixedBufferStream(&write_buffer);
|
||||
const writer = fbs.writer();
|
||||
|
||||
try writer.print("HTTP/1.1 200 OK\r\n", .{});
|
||||
try writer.print("Content-Type: {s}\r\n", .{content_type});
|
||||
try writer.print("Content-Length: {d}\r\n", .{response_body.len});
|
||||
try writer.print("\r\n", .{});
|
||||
try writer.print("{s}", .{response_body});
|
||||
|
||||
return fbs.getWritten();
|
||||
}
|
||||
|
||||
pub fn process(conn: std.net.Server.Connection) !void {
|
||||
defer conn.stream.close();
|
||||
|
||||
var arena = std.heap.ArenaAllocator.init(main.allocator);
|
||||
defer arena.deinit();
|
||||
|
||||
const allocator = arena.allocator();
|
||||
_ = allocator;
|
||||
|
||||
var running = true;
|
||||
while (running) {
|
||||
var header_end: ?usize = null;
|
||||
var request_len: usize = 0;
|
||||
|
||||
const request_head = blk: while (conn.stream.read(read_buffer[request_len..])) |len| {
|
||||
if (len == 0) {
|
||||
running = false;
|
||||
return;
|
||||
}
|
||||
|
||||
header_end = std.mem.indexOfPos(u8, &read_buffer, request_len, "\r\n\r\n");
|
||||
request_len += len;
|
||||
|
||||
if (header_end) |end| {
|
||||
break :blk read_buffer[0..end];
|
||||
}
|
||||
} else |err| {
|
||||
return err;
|
||||
};
|
||||
|
||||
const response = try http_200("text/plain; charset=utf-8", "PONG\n");
|
||||
|
||||
try conn.stream.writeAll(response);
|
||||
|
||||
if (request_len > request_head.len + 4) {
|
||||
@memmove(&read_buffer, read_buffer[request_head.len + 4 .. request_len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user