From cb2517bee240c592c07e77c1507877cf47ace553 Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sat, 15 Mar 2025 01:16:39 +0800 Subject: Separate paths into segments --- Makefile | 2 +- main.ha | 7 +++++-- templates/index.htmpl | 8 +++++++- url.ha | 15 +++++++++++++++ 4 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 url.ha diff --git a/Makefile b/Makefile index c32770f..df09cae 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -forge: main.ha templates.ha +forge: templates.ha *.ha hare build -o $@ . templates.ha: templates/*.htmpl diff --git a/main.ha b/main.ha index 39616b5..2c59c3d 100644 --- a/main.ha +++ b/main.ha @@ -10,6 +10,7 @@ use net::dial; use net::http; use net::ip; use net::tcp; +use net::uri; use os; use memio; use io; @@ -58,8 +59,10 @@ export fn main() void = { }; }; -export fn handlereq(conn: io::handle, request: *http::request) (void | io::error | nomem) = { +export fn handlereq(conn: io::handle, request: *http::request) (void | io::error | nomem | net::uri::invalid) = { htmpl::write(conn, "HTTP/1.1 200 OK\r\n")?; htmpl::write(conn, "Content-Type: text/html\r\n\r\n")?; - tp_index(conn)?; + let segments = segments_from_path(request.target.raw_path)?; + defer free_segments(segments); + tp_index(conn, segments)?; }; diff --git a/templates/index.htmpl b/templates/index.htmpl index e67cc09..1b4dd8b 100644 --- a/templates/index.htmpl +++ b/templates/index.htmpl @@ -1,4 +1,4 @@ -{{ define tp_index(handle: io::handle) (void | io::error | nomem) }} +{{ define tp_index(handle: io::handle, segments: []str) (void | io::error | nomem) }} @@ -7,6 +7,12 @@ {{ render _tp_header(handle, "test", "test") }} +

Path segments

+
diff --git a/url.ha b/url.ha new file mode 100644 index 0000000..3d7862f --- /dev/null +++ b/url.ha @@ -0,0 +1,15 @@ +use strings; +use net::uri; + +fn segments_from_path(s: str) ([]str | nomem | net::uri::invalid) = { + let sp: []str = strings::split(s, "/")?; + for (let i = 1z; i < len(sp); i += 1) + sp[i - 1] = net::uri::percent_decode(sp[i])?; + return sp[.. len(sp) - 1]; +}; + +fn free_segments(ss: []str) void = { + for (let s .. ss) { + free(s); + }; +}; -- cgit v1.2.3