wip html returning on GET to route

This commit is contained in:
Nathan Anderson
2023-11-10 16:26:37 -07:00
parent c19af600f2
commit 70fbe8668b
10 changed files with 294 additions and 152 deletions
+17
View File
@@ -0,0 +1,17 @@
const std = @import("std");
const one_megabyte: usize = 1024 * 1024;
const string = []const u8;
// Caller owns the returned StringArrayHashMap
pub fn open_html_load(allocator: std.mem.Allocator, filenames: []const []const u8) !std.StringArrayHashMap(string) {
var dir = std.fs.cwd();
var html_file_map = std.StringArrayHashMap(string).init(allocator);
for (filenames) |file_name| {
var f = try dir.openFile(file_name, .{});
var html_content = try f.readToEndAlloc(allocator, one_megabyte);
try html_file_map.putNoClobber(file_name, html_content);
}
return html_file_map;
}
View File
+7 -81
View File
@@ -1,72 +1,8 @@
const std = @import("std");
const http = std.http;
const log = std.log.scoped(.server);
const server_addr = "127.0.0.1";
const server_port = 8000;
// Run the server and handle incoming requests.
fn runServer(server: *http.Server, allocator: std.mem.Allocator) !void {
outer: while (true) {
// Accept incoming connection.
var response = try server.accept(.{
.allocator = allocator,
});
defer response.deinit();
while (response.reset() != .closing) {
// Handle errors during request processing.
response.wait() catch |err| switch (err) {
error.HttpHeadersInvalid => continue :outer,
error.EndOfStream => continue,
else => return err,
};
// Process the request.
try handleRequest(&response, allocator);
}
}
}
// Handle an individual request.
fn handleRequest(response: *http.Server.Response, allocator: std.mem.Allocator) !void {
// Log the request details.
log.info("{s} {s} {s}", .{ @tagName(response.request.method), @tagName(response.request.version), response.request.target });
// Read the request body.
const body = try response.reader().readAllAlloc(allocator, 8192);
defer allocator.free(body);
// Set "connection" header to "keep-alive" if present in request headers.
if (response.request.headers.contains("connection")) {
try response.headers.append("connection", "keep-alive");
}
// Check if the request target starts with "/get".
if (std.mem.startsWith(u8, response.request.target, "/get")) {
// Check if the request target contains "?chunked".
if (std.mem.indexOf(u8, response.request.target, "?chunked") != null) {
response.transfer_encoding = .chunked;
} else {
response.transfer_encoding = .{ .content_length = 10 };
}
// Set "content-type" header to "text/plain".
try response.headers.append("content-type", "text/plain");
// Write the response body.
try response.do();
if (response.request.method != .HEAD) {
try response.writeAll("Zig ");
try response.writeAll("Bits!\n");
try response.finish();
}
} else {
// Set the response status to 404 (not found).
response.status = .not_found;
try response.do();
}
}
const Zx = @import("zx.zig").Zx;
const index = @import("routes/index.zig");
pub fn main() !void {
// Create an allocator.
@@ -75,23 +11,13 @@ pub fn main() !void {
const allocator = gpa.allocator();
// Initialize the server.
var server = http.Server.init(allocator, .{ .reuse_address = true });
var server = Zx.init(allocator);
defer server.deinit();
// Log the server address and port.
log.info("Server is running at {s}:{d}", .{ server_addr, server_port });
try server.GET("/zig", index.getIndex);
// Parse the server address.
const address = try std.net.Address.parseIp(server_addr, server_port);
try server.listen(address);
// Run the server.
runServer(&server, allocator) catch |err| {
// Handle server errors.
log.err("server error: {}\n", .{err});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
std.os.exit(1);
server.runServer() catch |err| {
log.err("Server exited with err: {any}\nDumping trace:\n", .{err});
std.debug.dumpCurrentStackTrace(null);
};
}
+11
View File
@@ -0,0 +1,11 @@
const std = @import("std");
const http = std.http;
const zx = @import("../zx.zig");
pub fn getIndex(ctz: *zx.ZxContext) zx.ZxError!void {
ctz.json(.{ .success = true, .message = "hello did you get this?", .age = 1 }) catch |err| {
std.debug.print("Got error {any}\n", .{err});
return zx.ZxError.Unexpected;
};
return;
}
+193 -12
View File
@@ -1,32 +1,213 @@
const std = @import("std");
const options = @import("options");
const zx_utils = @import("htzx/utils.zig");
const markup_files = options.markup_files;
const http = std.http;
const log = std.log.scoped(.server);
const string = []const u8;
const server_addr = "127.0.0.1";
const server_port = 8000;
pub const ZxError = error{
DoError,
FinishError,
OutOfMemory,
RedefinedRoute,
Unexpected,
};
pub const ZxRouteFn = *const fn (*ZxContext) ZxError!void;
pub const Zx = struct {
server: http.Server,
allocator: std.mem.Allocator,
routes: std.StringArrayHashMap(ZxRouteFn),
html_files_map: std.StringArrayHashMap(string),
pub fn init( allocator: std.mem.Allocator,) Zx {
pub fn init(
allocator: std.mem.Allocator,
) Zx {
var server = http.Server.init(allocator, .{ .reuse_address = true });
defer server.deinit();
var routes = std.StringArrayHashMap(ZxRouteFn).init(allocator);
var html_files_map = std.StringArrayHashMap(string).init(allocator);
return .{ .server = server, .allocator = allocator, .routes = routes, .html_files_map = html_files_map };
}
// Log the server address and port.
pub fn deinit(zx: *Zx) void {
zx.server.deinit();
zx.routes.deinit();
// free html file content values
for (zx.html_files_map.keys()) |key| {
var entry = zx.html_files_map.getEntry(key);
zx.allocator.free(entry.?.value_ptr);
}
zx.html_files_map.deinit();
}
pub fn runServer(zx: *Zx) !void {
log.info("Server is running at {s}:{d}", .{ server_addr, server_port });
for (markup_files) |file| {
log.info("{s}", .{file});
}
zx.html_files_map = try zx_utils.open_html_load(zx.allocator, markup_files);
// Parse the server address.
const address = try std.net.Address.parseIp(server_addr, server_port);
try server.listen(address);
zx.server.listen(address) catch return ZxError.Unexpected;
// Run the server.
runServer(&server, allocator) catch |err| {
// Handle server errors.
log.err("server error: {}\n", .{err});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
outer: while (true) {
// Accept incoming connection.
var response = zx.server.accept(.{
.allocator = zx.allocator,
}) catch return ZxError.Unexpected;
defer response.deinit();
while (response.reset() != .closing) {
// Handle errors during request processing.
response.wait() catch |err| switch (err) {
error.HttpHeadersInvalid => continue :outer,
error.EndOfStream => continue,
else => return err,
};
// Process the request.
try handleRequest(zx, &response, zx.allocator);
}
std.os.exit(1);
};
}
}
pub fn POST(comptime path: string, handler: ZxRouteFn) void {
_ = handler;
_ = path;
}
pub fn GET(zx: *Zx, comptime path: string, handler: ZxRouteFn) ZxError!void {
zx.routes.putNoClobber(path, handler) catch |err| {
std.debug.print("{any}\nCant add another route at {s}\n", .{ err, path });
return ZxError.RedefinedRoute;
};
}
/// [/ <----------------------------------- \]
/// Order of operations: accept -> wait -> do [ -> write -> finish][ -> reset /]
/// \ -> read /
fn handleRequest(zx: *Zx, response: *http.Server.Response, allocator: std.mem.Allocator) ZxError!void {
// Read the request body.
const body = response.reader().readAllAlloc(allocator, 8192) catch return ZxError.Unexpected;
defer allocator.free(body);
// Log the request details.
log.info("{s} {s}", .{ @tagName(response.request.method), response.request.target });
// Set "connection" header to "keep-alive" if present in request headers.
if (response.request.headers.contains("connection")) {
response.headers.append("connection", "keep-alive") catch return ZxError.Unexpected;
}
response.headers.append("Server", "Htzx") catch return ZxError.Unexpected;
// if (std.mem.indexOf(u8, response.request.target, "?chunked") != null) {
// response.transfer_encoding = .chunked;
// } else {
// response.transfer_encoding = .{ .content_length = 10 };
// }
// Set "content-type" header to "text/plain".
// response.headers.append("content-type", "text/plain") catch return ZxError.Unexpected;
// Write the response body.
if (response.request.method != .HEAD) {
var ctz = ZxContext.init(allocator, response, body);
if (response.request.method == .GET and zx.has_html_route(response.request.target)) {
log.info("Returning html file at {s}...", .{response.request.target});
try zx.return_html(&ctz);
} else {
var handler = zx.routes.get(response.request.target);
if (handler) |h| {
h(&ctz) catch |err| {
errorHandler(response, err);
};
} else {
std.debug.print("No route defined for {s}\n", .{response.request.target});
response.status = .not_found;
response.do() catch return ZxError.DoError;
}
}
response.finish() catch |err| {
log.err("Got finish error {any}\n", .{err});
return ZxError.FinishError;
};
} else {
response.do() catch return ZxError.Unexpected;
response.finish() catch return ZxError.FinishError;
}
}
fn has_html_route(zx: *Zx, route_target: string) bool {
return zx.html_files_map.contains(route_target);
}
fn return_html(zx: *Zx, ctz: *ZxContext) ZxError!void {
var html = zx.html_files_map.get(ctz.response.request.target).?;
try ctz.html(html);
}
fn errorHandler(response: *http.Server.Response, err: ZxError) void {
log.err("Got error while handling route {any}\n", .{err});
response.status = .internal_server_error;
}
};
pub const ZxContext = struct {
allocator: std.mem.Allocator,
response: *http.Server.Response,
req_body: string,
pub fn init(alloc: std.mem.Allocator, res: *http.Server.Response, body: string) ZxContext {
return ZxContext{
.allocator = alloc,
.response = res,
.req_body = body,
};
}
/// Helper function to return JSON to the client
pub fn json(ctz: *ZxContext, content: anytype) ZxError!void {
// Add json header
ctz.response.headers.append("Content-Type", "application/json") catch return ZxError.Unexpected;
const json_content = std.json.stringifyAlloc(ctz.allocator, content, .{}) catch return ZxError.OutOfMemory;
defer ctz.allocator.free(json_content);
try ctz.respond(json_content);
}
test "json helper function" {}
pub fn html(ctz: *ZxContext, html_content: string) ZxError!void {
// Add html header
ctz.response.headers.append("Content-Type", "text/html") catch return ZxError.Unexpected;
try ctz.respond(html_content);
}
// Helper function to return body to the client
pub fn respond(ctz: *ZxContext, body: string) ZxError!void {
if (!ctz.response.headers.contains("Content-Type")) {
ctz.response.headers.append("Content-Type", "text/html") catch return ZxError.Unexpected;
}
ctz.response.transfer_encoding = .{ .content_length = body.len };
// Send headers
ctz.response.do() catch return ZxError.DoError;
// Send html body
ctz.response.writeAll(body) catch return ZxError.Unexpected;
}
};