I'm trying to write an API that is recievig JSON data, I was able to rcieve the data, but not sure how can I read it or extract its contents.
My code line is:
我正在尝试编写一个接收JSON数据的API,我能够接收数据,但不确定如何读取或提取其内容。我的代码行是:
pub fn post(response: *http.Server.Response) void {
response.do() catch |e| {
std.log.err("{any}", .{e});
};
if (response.request.method != .HEAD) {
std.log.debug("Prenting request details", .{});
std.log.info("{any}", .{response.request});
}
}
I sent the curl
command curl -X POST http://127.0.0.1:8000/post -H 'Content-Type: application/json' -d '{"login":"my_login", "password":"my_password"}'
And the output I got is:
我发送了cURL命令cURL-X POST http://127.0.0.1:8000/post-H‘Content-Type:APPLICATION/JSON’-d‘{“LOGIN”:“MY_LOGIN”,“PASSWORD”:“MY_PASSWORD”}’,得到的输出是:
debug: Prenting request details
info: http.Server.Request{ .method = http.Method.POST, .target = { 47, 112, 111, 115, 116 }, .version = http.Version.HTTP/1.1, .content_length = 46, .transfer_encoding = null, .transfer_compression = null, .headers = Host: 127.0.0.1:8000
User-Agent: curl/8.2.1
Accept: */*
Content-Type: application/json
Content-Length: 46
, .parser = http.protocol.HeadersParser{ .state = http.protocol.State.finished, .header_bytes_owned = true, .header_bytes = array_list.ArrayListAlignedUnmanaged(u8,null){ .items = { ... }, .capacity = 165 }, .max_header_bytes = 8192, .next_chunk_length = 0, .done = true }, .compression = http.Server.Compression{ .none = void } }
How can I read the JSON data from this response? and as a validation point, how can I check the Content-Type
, I can see it in the response but no idea how to handle it in the code?
如何从该响应中读取JSON数据?作为验证点,我如何检查Content-Type,我可以在响应中看到它,但不知道如何在代码中处理它?
更多回答
优秀答案推荐
You can read the request body from a reader
on std.http.Server.Response
:
您可以从std.http.Server.Response上的读取器读取请求正文:
const max_size = 8192;
const body = try response.reader().readAllAlloc(allocator, max_size);
defer allocator.free(body);
更多回答
我是一名优秀的程序员,十分优秀!