I am making a C++ wxWidgets application, my desktop program is an interface for an LLM chat external command-line application, called Ollama.
Ollama is a lightweight, extensible framework for building and running language models on the local machine. It provides a simple API for creating, running, and managing models, as well as a library of pre-built models that can be easily used in a variety of applications.
It works like this,
First, we run in one terminal: “ollama serve”, which in that terminal starts a server that listen all the commands and works as a webserver inside localhost, and the only way to turn it off is by killing the process.
Second, in another terminal, we can use “ollama run MODEL_NAME”, to start a chat with said model, communicating with the server using HTTP and JSON.
I Have a Network class using cpp-httplib, with methods like HTTPGet, HTTPPost and HTTPDelete, to deal with the HTTP requests.
And for the JSON part I am using nlohmann/json library.
Here’s a quick recap to make sure we’re both on the same page:
Ollama Framework: I am using the Ollama framework to build and run language models locally. The framework starts a server when you run ollama serve and it listens for commands, which you then interact with using HTTP requests.
Communication: For communication with the Ollama server, I have a Network class utilizing the cpp-httplib library to make HTTP requests (GET, POST, DELETE).
Data Handling: I am using the nlohmann/json library to handle JSON data, which is used for communication with the Ollama server.
I am planning to build a wxWidgets application that acts as an interface to communicate with the Ollama server, allowing you to interact with language models via HTTP and JSON.
Tell me if you understand my setup so we can continue.
Assistant
Yes, I understand your setup. Let's summarize it one more time to ensure we are aligned:
Setup Summary:
Ollama Framework:
Basic Usage:
ollama serve: Starts the server on localhost.
ollama run MODEL_NAME: Initiates chat with the specified model via the server.
Communication:
Library Used:cpp-httplib for making HTTP GET, POST, and DELETE requests to interact with the Ollama server.
Data Handling:
Library Used:nlohmann::json library for parsing and creating JSON data for communication.
GUI Framework:
Library Used: to create the desktop application's user interface.
User
Assistant
Got it, I understand the problem. You need to handle streaming responses from the Ollama server using the cpp-httplib library in such a way that your application can properly wait for and process multiple responses until the "done": true message is received.
In summary, you want to:
Send an HTTP POST request to initiate a chat.
Continuously read the streaming responses until a response with "done": true is received.
I will await your signal to proceed with showing your current code and the cpp-httplib headers. This will help ensure that any code or advice provided is accurate and contextually relevant to your existing setup.
Once you share the required code and headers, we'll proceed step-by-step to implement the correct approach for reading and handling these streaming responses.
User
Assistant
Thank you for sharing your Network class implementation. I noticed that you’re working with synchronous HTTP POST requests, but for handling streaming responses you’ll need to adjust your approach to continuously read responses until "done": true is received.
We will wait until you provide the cpp-httplib headers to understand its streaming capabilities, if any. However, based on common practices, it might involve utilizing a callback mechanism or similar to process chunks of data as they are received.
User
Assistant
Thank you for sharing part 1 of the cpp-httplib headers. I understand the necessity to process the headers in parts due to their length. I will wait for your signal indicating that all parts have been provided before we begin to modify your Network class for handling the multi-response streaming functionality.
Please continue to share the remaining parts of the headers, and I'll ensure to keep track of all details provided until we have the complete picture. Let me know when the full set of headers has been sent, and we'll proceed from there.
User
Assistant
Thank you for providing Part 2 of the cpp-httplib headers. Please continue to share the remaining parts. Once you have provided all the necessary parts, I will review them to understand how we can best utilize the streaming or chunked response handling capabilities of this library for your specific use case.
Please let me know once you have posted the final part of the headers, and we'll proceed from there.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You are planning to build a wxWidgets application that acts as an interface to communicate with the Ollama server, using HTTP and JSON to interact with language models.
With this understanding, you're looking to proceed with integrating these components to build a functional application.
How would you like to continue? Do you need help with:
Designing the wxWidgets UI?
Implementing specific functionalities within the GUI?
Integrating HTTP requests with wxWidgets?
Handling JSON responses?
Please specify how you'd like to proceed!
I already discussed this with another instance of you, and you spit wrong codes, probably with how the cpp-httplib is internally in your own memories, so I will post my code, and the library header, so you know what is the best way to approach this problem. So a few rules before we continue:
Don’t write code that you aren’t sure it is correct, don’t allucinate with what you think it is vs how is it, many things changed and your dataset could be wrong, so ask for clarification before going into the code rabbit hole.
Don’t write code repeating last parts, that means, don’t rewrite old code that is already working, only write the differences.
If you know about AI chat interfaces like chat gpt, there is a mode called streaming, were there is one http post message with the prompt and then several messages, each message with a part of the message called token. After every token is sent, there is a final message with a parameter done set to true.
In other words:
“done”: false // means there are still messages to receive and read
“done”: true, // means the message is done and now you can ask another question.
This is the documentation of a chat with streaming:
Chat Request (Streaming)
Request
Send a chat message with a streaming response.
curl http://localhost:11434/api/chat -d ‘{
“model”: “llama3”,
“messages”: [
{
“role”: “user”,
“content”: “why is the sky blue?”
}
]
}’
Response
A stream of JSON objects is returned:
So we need a way to deal with these multi-response messages, which I haven’t got it to work as the code is now. I think there should be a way to keep waiting for messages like in a while done != true.
Now let me know if you understand the problem, so I can post my own code and the cpp-httplib headers, do not write code just yet, wait until my signal!
Perfect, thanks for your understanding, here is my network class, wait until I post the library headers:
if (timeoutSec > 0)
{
client->set_connection_timeout(timeoutSec, 0);
client->set_read_timeout(timeoutSec, 0);
}
wxLogDebug(“Sending POST request to: %s%s with payload: %s”, host.c_str(), requestPath.c_str(), requestPayload.c_str());
auto res = client->Post(requestPath.c_str(), requestPayload.c_str(), contentType.c_str());
if (res) {
wxLogDebug(“Received response status: %d”, res->status);
if (res->status == 200 && !res->body.empty()) {
wxLogDebug(“Response body: %s”, res->body.c_str());
return res->body;
} else {
wxLogError(“HTTP POST request failed with status: %d”, res->status);
}
} else {
wxLogError(“HTTP POST request failed with status: %d”, res->status);
}
throw std::runtime_error("HTTP POST request failed with status: " + std::to_string(res ? res->status : 0));
}
Initial Observations and Clarifications
Synchronous Requests: Your current HTTPPost method is set up for a single, synchronous HTTP POST request.
Streaming Responses: We need a way to handle responses in chunks, continuously processing the incoming data from the server until we indicate that the message stream is complete.
Connection Persistence: We need to ensure the connection remains open to receive all parts of the streaming responses.
In the meantime, here are a few initial adjustments we might consider based on general HTTP client principles for handling streaming data:
Callback Mechanisms: Check if cpp-httplib (or the version you’re using) supports callback mechanisms for handling data streams.
Persistent Connection: Ensure that the HTTP connection remains open to continuously receive data.
Buffered Reading: Implement a loop to read data until the "done": true message is received.
Steps Ahead
Inspect Headers: Once you share the cpp-httplib headers, we will look for methods/functions that support streaming or chunked transfer encoding.
Modify HTTPPost Method: Adapt your HTTPPost method (or create a new method) to support streaming responses using the identified mechanisms.
Handling JSON parts: Parse and handle each JSON part of the response, accumulating the content until the complete message is received.
Please go ahead and share the cpp-httplib headers, and feel free to provide any additional context if needed. I'll wait for your next input to proceed accurately.
The library code is too long, so I will send it into several parts, I will give you the signal when the code is fully sent. You don't need to answer or reply me and waste bandwith between parts.
Server &set_exception_handler(ExceptionHandler handler);
Server &set_pre_routing_handler(HandlerWithResponse handler);
Server &set_post_routing_handler(Handler handler);
Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
Server &set_logger(Logger logger);
Server &set_address_family(int family);
Server &set_tcp_nodelay(bool on);
Server &set_socket_options(SocketOptions socket_options);
Server &set_default_headers(Headers headers);
Server &
set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
Server &set_keep_alive_max_count(size_t count);
Server &set_keep_alive_timeout(time_t sec);
Server &set_read_timeout(time_t sec, time_t usec = 0);
template <class Rep, class Period>
Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
Server &set_write_timeout(time_t sec, time_t usec = 0);
template <class Rep, class Period>
Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
Server &set_idle_interval(time_t sec, time_t usec = 0);
template <class Rep, class Period>
Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
Server &set_payload_max_length(size_t length);
bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
int bind_to_any_port(const std::string &host, int socket_flags = 0);
bool listen_after_bind();
bool listen(const std::string &host, int port, int socket_flags = 0);
Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
Server &set_error_handler_core(Handler handler, std::false_type);
socket_t create_server_socket(const std::string &host, int port,
int socket_flags,
SocketOptions socket_options) const;
int bind_internal(const std::string &host, int port, int socket_flags);
bool listen_internal();
inline const char *status_message(int status) {
switch (status) {
case StatusCode::Continue_100: return "Continue";
case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
case StatusCode::Processing_102: return "Processing";
case StatusCode::EarlyHints_103: return "Early Hints";
case StatusCode::OK_200: return "OK";
case StatusCode::Created_201: return "Created";
case StatusCode::Accepted_202: return "Accepted";
case StatusCode::NonAuthoritativeInformation_203:
return "Non-Authoritative Information";
case StatusCode::NoContent_204: return "No Content";
case StatusCode::ResetContent_205: return "Reset Content";
case StatusCode::PartialContent_206: return "Partial Content";
case StatusCode::MultiStatus_207: return "Multi-Status";
case StatusCode::AlreadyReported_208: return "Already Reported";
case StatusCode::IMUsed_226: return "IM Used";
case StatusCode::MultipleChoices_300: return "Multiple Choices";
case StatusCode::MovedPermanently_301: return "Moved Permanently";
case StatusCode::Found_302: return "Found";
case StatusCode::SeeOther_303: return "See Other";
case StatusCode::NotModified_304: return "Not Modified";
case StatusCode::UseProxy_305: return "Use Proxy";
case StatusCode::unused_306: return "unused";
case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
case StatusCode::BadRequest_400: return "Bad Request";
case StatusCode::Unauthorized_401: return "Unauthorized";
case StatusCode::PaymentRequired_402: return "Payment Required";
case StatusCode::Forbidden_403: return "Forbidden";
case StatusCode::NotFound_404: return "Not Found";
case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
case StatusCode::NotAcceptable_406: return "Not Acceptable";
case StatusCode::ProxyAuthenticationRequired_407:
return "Proxy Authentication Required";
case StatusCode::RequestTimeout_408: return "Request Timeout";
case StatusCode::Conflict_409: return "Conflict";
case StatusCode::Gone_410: return "Gone";
case StatusCode::LengthRequired_411: return "Length Required";
case StatusCode::PreconditionFailed_412: return "Precondition Failed";
case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
case StatusCode::UriTooLong_414: return "URI Too Long";
case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
case StatusCode::ExpectationFailed_417: return "Expectation Failed";
case StatusCode::ImATeapot_418: return "I'm a teapot";
case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
case StatusCode::Locked_423: return "Locked";
case StatusCode::FailedDependency_424: return "Failed Dependency";
case StatusCode::TooEarly_425: return "Too Early";
case StatusCode::UpgradeRequired_426: return "Upgrade Required";
case StatusCode::PreconditionRequired_428: return "Precondition Required";
case StatusCode::TooManyRequests_429: return "Too Many Requests";
case StatusCode::RequestHeaderFieldsTooLarge_431:
return "Request Header Fields Too Large";
case StatusCode::UnavailableForLegalReasons_451:
return "Unavailable For Legal Reasons";
case StatusCode::NotImplemented_501: return "Not Implemented";
case StatusCode::BadGateway_502: return "Bad Gateway";
case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
case StatusCode::HttpVersionNotSupported_505:
return "HTTP Version Not Supported";
case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
case StatusCode::LoopDetected_508: return "Loop Detected";
case StatusCode::NotExtended_510: return "Not Extended";
case StatusCode::NetworkAuthenticationRequired_511:
return "Network Authentication Required";
default:
case StatusCode::InternalServerError_500: return "Internal Server Error";
}
}
inline std::string to_string(const Error error) {
switch (error) {
case Error::Success: return "Success (no error)";
case Error::Connection: return "Could not establish connection";
case Error::BindIPAddress: return "Failed to bind IP address";
case Error::Read: return "Failed to read connection";
case Error::Write: return "Failed to write connection";
case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
case Error::Canceled: return "Connection handling canceled";
case Error::SSLConnection: return "SSL connection failed";
case Error::SSLLoadingCerts: return "SSL certificate loading failed";
case Error::SSLServerVerification: return "SSL server verification failed";
case Error::UnsupportedMultipartBoundaryChars:
return "Unsupported HTTP multipart boundary characters";
case Error::Compression: return "Compression failed";
case Error::ConnectionTimeout: return "Connection timed out";
case Error::ProxyConnection: return "Proxy connection failed";
case Error::Unknown: return "Unknown";
default: break;
}
inline bool is_hex(char c, int &v) {
if (0x20 <= c && isdigit(c)) {
v = c - '0';
return true;
} else if ('A' <= c && c <= 'F') {
v = c - 'A' + 10;
return true;
} else if ('a' <= c && c <= 'f') {
v = c - 'a' + 10;
return true;
}
return false;
}
inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
int &val) {
if (i >= s.size()) { return false; }
val = 0;
for (; cnt; i++, cnt--) {
if (!s[i]) { return false; }
auto v = 0;
if (is_hex(s[i], v)) {
val = val * 16 + v;
} else {
return false;
}
}
return true;
}
inline std::string from_i_to_hex(size_t n) {
static const auto charset = "0123456789abcdef";
std::string ret;
do {
ret = charset[n & 15] + ret;
n >>= 4;
} while (n > 0);
return ret;
}
while (i < path.size() && path[i] == '/') {
i++;
}
while (i < path.size()) {
auto beg = i;
while (i < path.size() && path[i] != '/') {
if (path[i] == '\0') {
return false;
} else if (path[i] == '\') {
return false;
}
i++;
}
code
auto len = i - beg;
assert(len > 0);
if (!path.compare(beg, len, ".")) {
;
} else if (!path.compare(beg, len, "..")) {
if (level == 0) { return false; }
level--;
} else {
level++;
}
while (i < path.size() && path[i] == '/') {
i++;
}
for (size_t i = 0; s[i]; i++) {
switch (s[i]) {
case ' ': result += "%20"; break;
case '+': result += "%2B"; break;
case '\r': result += "%0D"; break;
case '\n': result += "%0A"; break;
case ''': result += "%27"; break;
case ',': result += "%2C"; break;
case ';': result += "%3B"; break;
default:
auto c = static_cast<uint8_t>(s[i]);
if (c >= 0x80) {
result += '%';
char hex[4];
auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
assert(len == 2);
result.append(hex, static_cast<size_t>(len));
} else {
result += s[i];
}
break;
}
}
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '%' && i + 1 < s.size()) {
if (s[i + 1] == 'u') {
auto val = 0;
if (from_hex_to_i(s, i + 2, 4, val)) {
char buff[4];
size_t len = to_utf8(val, buff);
if (len > 0) { result.append(buff, len); }
i += 5;
} else {
result += s[i];
}
} else {
auto val = 0;
if (from_hex_to_i(s, i + 1, 2, val)) {
result += static_cast(val);
i += 2;
} else {
result += s[i];
}
}
} else if (convert_plus_to_space && s[i] == '+') {
result += ' ';
} else {
result += s[i];
}
}
inline std::string file_extension(const std::string &path) {
std::smatch m;
static auto re = std::regex("\.([a-zA-Z0-9]+)$");
if (std::regex_search(path, m, re)) { return m[1].str(); }
return std::string();
}
inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
size_t right) {
while (b + left < e && is_space_or_tab(b[left])) {
left++;
}
while (right > 0 && is_space_or_tab(b[right - 1])) {
right--;
}
return std::make_pair(left, right);
}
while (e ? (b + i < e) : (b[i] != '\0')) {
if (b[i] == d && count < m) {
auto r = trim(b, e, beg, i);
if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
beg = i + 1;
count++;
}
i++;
}
if (i) {
auto r = trim(b, e, beg, i);
if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
}
}
if (getaddrinfo(node, service.c_str(), &hints, &result)) {
res_init();
return INVALID_SOCKET;
}
for (auto rp = result; rp; rp = rp->ai_next) {
auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == INVALID_SOCKET) { continue; }
code
if (tcp_nodelay) {
auto yes = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const void *>(&yes), sizeof(yes));
}
if (socket_options) { socket_options(sock); }
if (rp->ai_family == AF_INET6) {
auto no = 0;
setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<const void *>(&no), sizeof(no));
}
if (bind_or_connect(sock, *rp)) {
freeaddrinfo(result);
return sock;
}
close_socket(sock);
if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; }
auto ret = false;
for (auto rp = result; rp; rp = rp->ai_next) {
const auto &ai = *rp;
if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
ret = true;
break;
}
}
case "css"_t: return "text/css";
case "csv"_t: return "text/csv";
case "htm"_t:
case "html"_t: return "text/html";
case "js"_t:
case "mjs"_t: return "text/javascript";
case "txt"_t: return "text/plain";
case "vtt"_t: return "text/vtt";
case "apng"_t: return "image/apng";
case "avif"_t: return "image/avif";
case "bmp"_t: return "image/bmp";
case "gif"_t: return "image/gif";
case "png"_t: return "image/png";
case "svg"_t: return "image/svg+xml";
case "webp"_t: return "image/webp";
case "ico"_t: return "image/x-icon";
case "tif"_t: return "image/tiff";
case "tiff"_t: return "image/tiff";
case "jpg"_t:
case "jpeg"_t: return "image/jpeg";
case "mp4"_t: return "video/mp4";
case "mpeg"_t: return "video/mpeg";
case "webm"_t: return "video/webm";
case "mp3"_t: return "audio/mp3";
case "mpga"_t: return "audio/mpeg";
case "weba"_t: return "audio/webm";
case "wav"_t: return "audio/wave";
case "otf"_t: return "font/otf";
case "ttf"_t: return "font/ttf";
case "woff"_t: return "font/woff";
case "woff2"_t: return "font/woff2";
case "7z"_t: return "application/x-7z-compressed";
case "atom"_t: return "application/atom+xml";
case "pdf"_t: return "application/pdf";
case "json"_t: return "application/json";
case "rss"_t: return "application/rss+xml";
case "tar"_t: return "application/x-tar";
case "xht"_t:
case "xhtml"_t: return "application/xhtml+xml";
case "xslt"_t: return "application/xslt+xml";
case "xml"_t: return "application/xml";
case "gz"_t: return "application/gzip";
case "zip"_t: return "application/zip";
case "wasm"_t: return "application/wasm";
}
}
inline bool can_compress_content_type(const std::string &content_type) {
using udl::operator""_t;
auto tag = str2tag(content_type);
switch (tag) {
case "image/svg+xml"_t:
case "application/javascript"_t:
case "application/json"_t:
case "application/xml"_t:
case "application/protobuf"_t:
case "application/xhtml+xml"_t: return true;
default:
return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t;
}
}
inline EncodingType encoding_type(const Request &req, const Response &res) {
auto ret =
detail::can_compress_content_type(res.get_header_value("Content-Type"));
if (!ret) { return EncodingType::None; }
const auto &s = req.get_header_value("Accept-Encoding");
(void)(s);
uint64_t r = 0;
while (r < len) {
auto read_len = static_cast<size_t>(len - r);
auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
if (n <= 0) { return false; }
code
if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
r += static_cast<uint64_t>(n);
if (progress) {
if (!progress(r, len)) { return false; }
}
}
return true;
}
inline void skip_content_with_length(Stream &strm, uint64_t len) {
char buf[CPPHTTPLIB_RECV_BUFSIZ];
uint64_t r = 0;
while (r < len) {
auto read_len = static_cast<size_t>(len - r);
auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
if (n <= 0) { return; }
r += static_cast<uint64_t>(n);
}
}
inline bool read_content_without_length(Stream &strm,
ContentReceiverWithProgress out) {
char buf[CPPHTTPLIB_RECV_BUFSIZ];
uint64_t r = 0;
for (;;) {
auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
if (n <= 0) { return true; }
code
if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
r += static_cast<uint64_t>(n);
}
return true;
}
template
inline bool read_content_chunked(Stream &strm, T &x,
ContentReceiverWithProgress out) {
const auto bufsiz = 16;
char buf[bufsiz];
inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
auto valid = true;
for (size_t i = 0; i < boundary.size(); i++) {
auto c = boundary[i];
if (!std::isalnum(c) && c != '-' && c != '_') {
valid = false;
break;
}
}
return valid;
}
template
inline std::string
serialize_multipart_formdata_item_begin(const T &item,
const std::string &boundary) {
std::string body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name="" + item.name + """;
if (!item.filename.empty()) {
body += "; filename="" + item.filename + """;
}
body += "\r\n";
if (!item.content_type.empty()) {
body += "Content-Type: " + item.content_type + "\r\n";
}
body += "\r\n";
for (const auto &item : items) {
body += serialize_multipart_formdata_item_begin(item, boundary);
body += item.content + serialize_multipart_formdata_item_end();
}
if (finish) { body += serialize_multipart_formdata_finish(boundary); }
inline std::string make_content_range_header_field(
const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
auto st = offset_and_length.first;
auto ed = st + offset_and_length.second - 1;
std::string field = "bytes ";
field += std::to_string(st);
field += "-";
field += std::to_string(ed);
field += "/";
field += std::to_string(content_length);
return field;
}
inline std::pair<std::string, std::string>
make_range_header(const Ranges &ranges) {
std::string field = "bytes=";
auto i = 0;
for (const auto &r : ranges) {
if (i != 0) { field += ", "; }
if (r.first != -1) { field += std::to_string(r.first); }
field += '-';
if (r.second != -1) { field += std::to_string(r.second); }
i++;
}
return std::make_pair("Range", std::move(field));
}