commit bcc284ab8e7abda0c6386b1c18cdabe5a4f994b6 from: Omar Polo date: Thu Dec 21 11:26:20 2023 UTC start to use the http APIs commit - 924d1172de22bbaeae45ce6cca6d1b85358f84a9 commit + bcc284ab8e7abda0c6386b1c18cdabe5a4f994b6 blob - 1f0ee772f825b965a62afaa96979fa29e9704a3a blob + 550dfb999dd95169e43765e3decb35e4f334e368 --- shinsha.ha +++ shinsha.ha @@ -10,31 +10,8 @@ use os; use unix::signal; use ev; +use http; -fn handleio(fp: io::file, event: ev::event, data: nullable *opaque) void = { - let buf: [1024]u8 = [0...]; - match(io::read(fp, buf)!) { - case let n: size => - io::write(fp, buf[..n])!; - case io::EOF => - log::printfln("EOF; closing client"); - ev::del(fp); - io::close(fp)!; - }; -}; - -fn accept(fp: io::file, event: ev::event, data: nullable *opaque) void = { - let sock = match(net::accept(fp, net::sockflag::NONBLOCK)) { - case let err: net::error => - return; - case let sock: net::socket => - yield sock; - }; - - log::printfln("accepted a new client"); - ev::add(sock, ev::READ, &handleio, null); -}; - fn sighandler(sig: signal::sig, data: nullable *opaque) void = { // Normal signal handler rules don't apply because ev // decouples for us. @@ -48,6 +25,19 @@ fn sighandler(sig: signal::sig, data: nullable *opaque log::fatalf("unexpected {}", signal::signame(sig)); }; +fn homepage(clt: *http::client) (void | http::error) = { + http::reply(clt, 200, "OK")?; + http::header(clt, "Content-Type", "text/plain")?; + http::write(clt, "こんにちは世界!\n")?; + http::write(clt, "シンシャです。\n")?; +}; + +fn page2(clt: *http::client) (void | http::error) = { + http::reply(clt, 200, "OK")?; + http::header(clt, "Content-Type", "text/plain")?; + http::write(clt, "Pagina 2\n")?; +}; + export fn main() void = { const cmd = getopt::parse(os::args, "web manga reader", @@ -73,6 +63,7 @@ export fn main() void = { log::printfln("should use debug {} and verbose {}", debug, verbose); + // TODO: would be nice to do http::listen("localhost:9090")!; const port = 9090u16; const sock = match (tcp::listen(ip::LOCAL_V4, port, tcp::reuseaddr)) { case let sock: net::socket => @@ -83,8 +74,11 @@ export fn main() void = { }; defer net::close(sock)!; - ev::add(sock, ev::READ, &accept, null); + http::listen_sock(sock); + http::handle("/", &homepage); + http::handle("/2", &page2); + ev::signal(signal::sig::INT, &sighandler, null)!; ev::signal(signal::sig::TERM, &sighandler, null)!;