Last active
November 29, 2020 13:54
-
-
Save xspager/870ae73b270b5e5108d7ff4e708fb596 to your computer and use it in GitHub Desktop.
SerenityOS "hget"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <AK/ByteBuffer.h> | |
#include <AK/SharedBuffer.h> | |
#include <AK/URL.h> | |
#include <LibCore/ArgsParser.h> | |
#include <LibCore/EventLoop.h> | |
#include <LibCore/File.h> | |
#include <LibProtocol/Client.h> | |
#include <LibProtocol/Download.h> | |
#include <stdio.h> | |
static void do_write(const ByteBuffer& payload) | |
{ | |
size_t length_remaining = payload.size(); | |
size_t length_written = 0; | |
while (length_remaining > 0) { | |
auto nwritten = fwrite(payload.offset_pointer(length_written), sizeof(char), length_remaining, stdout); | |
if (nwritten > 0) { | |
length_remaining -= nwritten; | |
length_written += nwritten; | |
continue; | |
} | |
if (feof(stdout)) { | |
fprintf(stderr, "pro: unexpected eof while writing\n"); | |
return; | |
} | |
if (ferror(stdout)) { | |
fprintf(stderr, "pro: error while writing\n"); | |
return; | |
} | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
const char* url_str = nullptr; | |
Core::ArgsParser args_parser; | |
args_parser.add_positional_argument(url_str, "URL to download from", "url"); | |
args_parser.parse(argc, argv); | |
URL url(url_str); | |
if (!url.is_valid()) { | |
fprintf(stderr, "'%s' is not a valid URL\n", url_str); | |
return 1; | |
} | |
Core::EventLoop loop; | |
auto protocol_client = Protocol::Client::construct(); | |
auto m_download = protocol_client->start_download("GET", url_str); | |
ASSERT(m_download); | |
m_download->on_progress = [](Optional<u32> total_size, u32 downloaded_size) { | |
(void)total_size; | |
(void)downloaded_size; | |
fprintf(stdout, "progres..."); | |
}; | |
m_download->on_finish = [&](bool success, auto& payload, auto payload_storage, auto& response_headers, auto) { | |
(void) payload_storage; | |
for(auto& header: response_headers){ | |
fprintf(stdout, "%s: %s\n", header.key.characters(), header.value.characters()); | |
} | |
if (success) { | |
do_write(payload); | |
} else { | |
fprintf(stderr, "fail\n"); | |
} | |
loop.quit(0); | |
}; | |
return loop.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment