1
Fork 0

parse and dump json

This commit is contained in:
Jan-Erik Rediger 2024-05-28 20:47:57 +02:00
parent b339cec7e9
commit cf699ad928
3 changed files with 44 additions and 3 deletions

3
.gitmodules vendored
View file

@ -4,3 +4,6 @@
[submodule "backend/vendor/hare-logfmt"]
path = backend/vendor/hare-logfmt
url = https://git.sr.ht/~blainsmith/hare-logfmt
[submodule "backend/vendor/hare-json"]
path = backend/vendor/hare-json
url = https://git.sr.ht/~sircmpwn/hare-json

View file

@ -15,6 +15,7 @@ use thread;
use time;
use log::logfmt;
use log;
use encoding::json;
const usage: [_]getopt::help = [
"HTTP server",
@ -83,6 +84,13 @@ fn handle_req(arg: nullable *opaque) void = {
handle_notfound(&buf, serv_req);
return;
};
case "POST" =>
switch (request.target.path) {
case "/v1/exec" => handle_exec(&buf, serv_req);
case =>
handle_notfound(&buf, serv_req);
return;
};
case "OPTIONS" =>
handle_cors(&buf, serv_req);
return;
@ -119,9 +127,8 @@ export fn handle_cors(buf: *io::stream, serv_req: *http::server_request) void =
void,
("Content-Length", "0"),
("access-control-allow-origin", "*"),
("vary", "origin, access-control-request-method, access-control-request-headers"),
("access-control-allow-methods", "*"),
("access-control-allow-headers", "*"),
("access-control-allow-methods", "options, post"),
("access-control-allow-headers", "authorization, content-type")
)!;
return;
@ -135,6 +142,36 @@ export fn handle_cors(buf: *io::stream, serv_req: *http::server_request) void =
)!;
};
export fn handle_exec(buf: *io::stream, serv_req: *http::server_request) void = {
let request = serv_req.request;
let payload = match (request.body) {
case void =>
http::response_write(
serv_req.socket,
http::STATUS_BAD_REQUEST,
void,
("Content-Length", "0")
)!;
return;
case let body: io::handle =>
let payload = json::load(body)!;
yield payload;
};
json::dump(buf, payload)!;
http::response_write(
serv_req.socket,
http::STATUS_OK,
buf,
("Content-Type", "application/json"),
("access-control-allow-origin", "*"),
("access-control-allow-methods", "options, post"),
("access-control-allow-headers", "authorization, content-type")
)!;
};
export fn handle_index(buf: *io::stream, request: *http::request) void = {
fmt::fprintfln(buf, "Method: {}", request.method)!;
fmt::fprintfln(buf, "Path: {}", request.target.path)!;

1
backend/vendor/hare-json vendored Submodule

@ -0,0 +1 @@
Subproject commit b6aeae96199607a1f3b4d437d5c99f821bd6a6b6