Merge pull request #613 from MihailRis/update-network

Add 'data' argument to network error callback
This commit is contained in:
MihailRis 2025-09-16 23:40:25 +03:00 committed by GitHub
commit c5f10b8395
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 51 additions and 53 deletions

View File

@ -11,9 +11,9 @@ network.get(
-- Function to call when response is received -- Function to call when response is received
callback: function(str), callback: function(str),
-- Error handler -- Error handler
[optional] onfailure: function(int), [optional] onfailure: function(int, str),
-- List of additional request headers -- List of additional request headers
[optional] headers: table<string> [optional] headers: table<str>
) )
-- Example: -- Example:
@ -24,9 +24,9 @@ end)
-- A variant for binary files, with a byte array instead of a string in the response. -- A variant for binary files, with a byte array instead of a string in the response.
network.get_binary( network.get_binary(
url: str, url: str,
callback: function(table|ByteArray), callback: function(ByteArray),
[optional] onfailure: function(int), [optional] onfailure: function(int, str),
[optional] headers: table<string> [optional] headers: table<str>
) )
-- Performs a POST request to the specified URL. -- Performs a POST request to the specified URL.
@ -36,13 +36,13 @@ network.get_binary(
network.post( network.post(
url: str, url: str,
-- Request body as a table (will be converted to JSON) or string -- Request body as a table (will be converted to JSON) or string
body: table|string, body: table|str,
-- Function called when response is received -- Function called when response is received
callback: function(str), callback: function(str),
-- Error handler -- Error handler
[optional] onfailure: function(int), [optional] onfailure: function(int, str),
-- List of additional request headers -- List of additional request headers
[optional] headers: table<string> [optional] headers: table<str>
) )
``` ```

View File

@ -11,9 +11,9 @@ network.get(
-- Функция, вызываемая при получении ответа -- Функция, вызываемая при получении ответа
callback: function(str), callback: function(str),
-- Обработчик ошибок -- Обработчик ошибок
[опционально] onfailure: function(int), [опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса -- Список дополнительных заголовков запроса
[опционально] headers: table<string> [опционально] headers: table<str>
) )
-- Пример: -- Пример:
@ -24,9 +24,9 @@ end)
-- Вариант для двоичных файлов, с массивом байт вместо строки в ответе. -- Вариант для двоичных файлов, с массивом байт вместо строки в ответе.
network.get_binary( network.get_binary(
url: str, url: str,
callback: function(table|ByteArray), callback: function(ByteArray),
[опционально] onfailure: function(int), [опционально] onfailure: function(int, Bytearray),
[опционально] headers: table<string> [опционально] headers: table<str>
) )
-- Выполняет POST запрос к указанному URL. -- Выполняет POST запрос к указанному URL.
@ -36,13 +36,13 @@ network.get_binary(
network.post( network.post(
url: str, url: str,
-- Тело запроса в виде таблицы, конвертируемой в JSON или строки -- Тело запроса в виде таблицы, конвертируемой в JSON или строки
body: table|string, body: table|str,
-- Функция, вызываемая при получении ответа -- Функция, вызываемая при получении ответа
callback: function(str), callback: function(str),
-- Обработчик ошибок -- Обработчик ошибок
[опционально] onfailure: function(int), [опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса -- Список дополнительных заголовков запроса
[опционально] headers: table<string> [опционально] headers: table<str>
) )
``` ```

View File

@ -273,7 +273,7 @@ network.__process_events = function()
_http_response_callbacks[event[3]] = nil _http_response_callbacks[event[3]] = nil
_http_error_callbacks[event[3]] = nil _http_error_callbacks[event[3]] = nil
if callback then if callback then
callback(event[2]) callback(event[2], event[4])
end end
end end
end end

View File

@ -88,27 +88,24 @@ static int perform_get(lua::State* L, network::Network& network, bool binary) {
int currentRequestId = request_id++; int currentRequestId = request_id++;
network.get(url, [currentRequestId, binary](std::vector<char> bytes) { network.get(
url,
[currentRequestId, binary](std::vector<char> bytes) {
push_event(NetworkEvent( push_event(NetworkEvent(
RESPONSE, RESPONSE,
ResponseEventDto { ResponseEventDto {
200, 200, binary, currentRequestId, std::move(bytes)}
binary,
currentRequestId,
std::move(bytes)
}
)); ));
}, [currentRequestId](int code) { },
[currentRequestId, binary](int code, std::vector<char> bytes) {
push_event(NetworkEvent( push_event(NetworkEvent(
RESPONSE, RESPONSE,
ResponseEventDto { ResponseEventDto {
code, code, binary, currentRequestId, std::move(bytes)}
false,
currentRequestId,
{}
}
)); ));
}, std::move(headers)); },
std::move(headers)
);
return lua::pushinteger(L, currentRequestId); return lua::pushinteger(L, currentRequestId);
} }
@ -138,21 +135,17 @@ static int l_post(lua::State* L, network::Network& network) {
url, url,
string, string,
[currentRequestId](std::vector<char> bytes) { [currentRequestId](std::vector<char> bytes) {
auto buffer = std::make_shared<util::Buffer<ubyte>>(
reinterpret_cast<const ubyte*>(bytes.data()), bytes.size()
);
push_event(NetworkEvent( push_event(NetworkEvent(
RESPONSE, RESPONSE,
ResponseEventDto { ResponseEventDto {
200, 200, false, currentRequestId, std::move(bytes)}
false,
currentRequestId,
std::vector<char>(buffer->begin(), buffer->end())}
)); ));
}, },
[currentRequestId](int code) { [currentRequestId](int code, std::vector<char> bytes) {
push_event(NetworkEvent( push_event(NetworkEvent(
RESPONSE, ResponseEventDto {code, false, currentRequestId, {}} RESPONSE,
ResponseEventDto {
code, false, currentRequestId, std::move(bytes)}
)); ));
}, },
std::move(headers) std::move(headers)

View File

@ -173,7 +173,7 @@ public:
auto message = curl_multi_strerror(res); auto message = curl_multi_strerror(res);
logger.error() << message << " (" << url << ")"; logger.error() << message << " (" << url << ")";
if (onReject) { if (onReject) {
onReject(HTTP_BAD_GATEWAY); onReject(HTTP_BAD_GATEWAY, {});
} }
url = ""; url = "";
} }
@ -188,7 +188,7 @@ public:
auto message = curl_multi_strerror(res); auto message = curl_multi_strerror(res);
logger.error() << message << " (" << url << ")"; logger.error() << message << " (" << url << ")";
if (onReject) { if (onReject) {
onReject(HTTP_BAD_GATEWAY); onReject(HTTP_BAD_GATEWAY, {});
} }
curl_multi_remove_handle(multiHandle, curl); curl_multi_remove_handle(multiHandle, curl);
url = ""; url = "";
@ -213,9 +213,14 @@ public:
onResponse(std::move(buffer)); onResponse(std::move(buffer));
} }
} else { } else {
logger.error() << "response code " << response << " (" << url << ")"; logger.error()
<< "response code " << response << " (" << url << ")"
<< (buffer.empty()
? ""
: std::to_string(buffer.size()) + " byte(s)");
totalDownload += buffer.size();
if (onReject) { if (onReject) {
onReject(response); onReject(response, std::move(buffer));
} }
} }
url = ""; url = "";

View File

@ -11,7 +11,7 @@
namespace network { namespace network {
using OnResponse = std::function<void(std::vector<char>)>; using OnResponse = std::function<void(std::vector<char>)>;
using OnReject = std::function<void(int)>; using OnReject = std::function<void(int, std::vector<char>)>;
using ConnectCallback = std::function<void(u64id_t, u64id_t)>; using ConnectCallback = std::function<void(u64id_t, u64id_t)>;
using ServerDatagramCallback = std::function<void(u64id_t sid, const std::string& addr, int port, const char* buffer, size_t length)>; using ServerDatagramCallback = std::function<void(u64id_t sid, const std::string& addr, int port, const char* buffer, size_t length)>;
using ClientDatagramCallback = std::function<void(u64id_t cid, const char* buffer, size_t length)>; using ClientDatagramCallback = std::function<void(u64id_t cid, const char* buffer, size_t length)>;

View File

@ -16,7 +16,7 @@ TEST(curltest, curltest) {
auto view = std::string_view(data.data(), data.size()); auto view = std::string_view(data.data(), data.size());
auto value = json::parse(view); auto value = json::parse(view);
std::cout << value << std::endl; std::cout << value << std::endl;
}, [](auto){} }, [](auto, auto){}
); );
std::cout << "upload: " << network->getTotalUpload() << " B" << std::endl; std::cout << "upload: " << network->getTotalUpload() << " B" << std::endl;
std::cout << "download: " << network->getTotalDownload() << " B" << std::endl; std::cout << "download: " << network->getTotalDownload() << " B" << std::endl;