From 7a24ef3f09d81d3bcaf25473efea983ecfefa62f Mon Sep 17 00:00:00 2001 From: Jan-Erik Rediger Date: Sat, 1 Jun 2024 16:39:49 +0200 Subject: [PATCH] handle files and index --- backend/cmd/httpd/main.ha | 63 ++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 38 deletions(-) diff --git a/backend/cmd/httpd/main.ha b/backend/cmd/httpd/main.ha index 32b78ba..13b6fa8 100644 --- a/backend/cmd/httpd/main.ha +++ b/backend/cmd/httpd/main.ha @@ -101,10 +101,27 @@ fn handle_req(arg: nullable *opaque) void = { }; }; -export fn handle_file(buf: *memio::stream, serv_req: *http::server_request) void = { +fn handle_index(buf: *io::stream, serv_req: *http::server_request) void = { + let request = serv_req.request; + + let fp = os::open("index.html")!; + defer io::close(fp)!; + let filecontent = io::drain(fp)!; + defer free(filecontent); + + io::writeall(buf, filecontent)!; + + http::response_write( + serv_req.socket, + http::STATUS_OK, + buf, + ("Content-Type", "text/html; charset=utf-8") + )!; +}; + +fn handle_file(buf: *memio::stream, serv_req: *http::server_request) void = { let request = &serv_req.request; - fmt::printfln("handling file for path: {}", request.target.path)!; let pathbuf = strings::toutf8(request.target.path); if (bytes::contains(pathbuf[1..], '/')) { fmt::printfln("additional slash. not handling that.")!; @@ -130,7 +147,12 @@ export fn handle_file(buf: *memio::stream, serv_req: *http::server_request) void }; let filename = path::basename(request.target.path); - let fp = os::open(filename)!; + let fp = match (os::open(filename)) { + case let fp: io::file => yield fp; + case => + handle_notfound(buf, serv_req); + return; + }; defer io::close(fp)!; let filecontent = io::drain(fp)!; defer free(filecontent); @@ -260,38 +282,3 @@ export fn handle_exec(buf: *io::stream, serv_req: *http::server_request) void = ("access-control-allow-headers", "authorization, content-type") )!; }; - -export fn handle_index(buf: *io::stream, serv_req: *http::server_request) void = { - let request = serv_req.request; - - fmt::fprintfln(buf, "Method: {}", request.method)!; - fmt::fprintfln(buf, "Path: {}", request.target.path)!; - fmt::fprintfln(buf, "Fragment: {}", request.target.fragment)!; - fmt::fprintfln(buf, "Query: {}", request.target.query)!; - fmt::fprintfln(buf, "Headers: < void; - case let body: io::handle => - fmt::fprintfln(buf, "Body: < - fmt::fprintln(buf, strings::fromutf8(line)!)!; - break; - case io::EOF => - break; - }; - }; - fmt::fprintfln(buf, "EOF")!; - }; - - http::response_write( - serv_req.socket, - http::STATUS_OK, - buf, - ("Content-Type", "text/plain") - )!; -};