Skip to content

Commit

Permalink
Optimize http_client code
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Dec 9, 2024
1 parent 709a5cd commit 67ad28a
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions ext-src/swoole_http_client_coro.cc
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ class Client {
bool in_callback = false;
bool has_upload_files = false;

File *download_file = nullptr; // save http response to file
zend::String download_file_name; // unlink the file on error
std::shared_ptr<File> download_file; // save http response to file
zend::String download_file_name; // unlink the file on error
zend_long download_offset = 0;

/* safety zval */
Expand Down Expand Up @@ -474,6 +474,14 @@ static int http_parser_on_headers_complete(swoole_http_parser *parser) {
return 0;
}

static inline ssize_t http_client_co_write(int sockfd, const void *buf, size_t count) {
#ifdef SW_USE_IOURING
return swoole_coroutine_iouring_write(sockfd, buf, count);
#else
return swoole_coroutine_write(sockfd, buf, count);
#endif
}

static int http_parser_on_body(swoole_http_parser *parser, const char *at, size_t length) {
Client *http = (Client *) parser->data;
if (http->write_func) {
Expand Down Expand Up @@ -505,7 +513,7 @@ static int http_parser_on_body(swoole_http_parser *parser, const char *at, size_
if (http->download_file_name.get() && http->body->length > 0) {
if (http->download_file == nullptr) {
char *download_file_name = http->download_file_name.val();
std::unique_ptr<File> fp(new File(download_file_name, O_CREAT | O_WRONLY, 0664));
std::shared_ptr<File> fp = std::make_shared<File>(download_file_name, O_CREAT | O_WRONLY, 0664);
if (!fp->ready()) {
swoole_sys_warning("open(%s, O_CREAT | O_WRONLY) failed", download_file_name);
return -1;
Expand All @@ -521,9 +529,9 @@ static int http_parser_on_body(swoole_http_parser *parser, const char *at, size_
return -1;
}
}
http->download_file = fp.release();
http->download_file = fp;
}
if (swoole_coroutine_write(http->download_file->get_fd(), SW_STRINGL(http->body)) !=
if (http_client_co_write(http->download_file->get_fd(), SW_STRINGL(http->body)) !=
(ssize_t) http->body->length) {
return -1;
}
Expand Down Expand Up @@ -1682,8 +1690,7 @@ void Client::reset() {
zend_update_property_null(swoole_http_client_coro_ce, SW_Z8_OBJ_P(zobject), ZEND_STRL("uploadFiles"));
}
if (download_file != nullptr) {
delete download_file;
download_file = nullptr;
download_file.reset();
download_file_name.release();
download_offset = 0;
zend_update_property_null(swoole_http_client_coro_ce, SW_Z8_OBJ_P(zobject), ZEND_STRL("downloadFile"));
Expand Down

0 comments on commit 67ad28a

Please sign in to comment.