cpp-httplib를 사용하여 서버 이벤트를 수신하는 경우 예제 및 구현이 GET 방식으로만 되어 있다. 하지만 POST 를이용하여 작업해야 하는 경우도 있으므로 cpp-httplib를 약간 수정하여 POST로 이벤트를 연속으로 수신하는 방법을 구현해 본다.
이벤트를 연속으로 수신하는 것는 content receiver 를 사용해야 한다. 이를 위해 POST에 Client와 ClientImpl 에 아래와 같이 POST 함수를 추가한다.
class Client {
:
Result Post(const std::string& path, const Headers& headers, const char* body,
size_t content_length, ContentReceiver content_receiver);
함수구현:
inline Result Client::Post(const std::string& path, const Headers& headers,
const char* body, size_t content_length,
ContentReceiver content_receiver) {
return cli_->Post(path, headers, body, content_length, content_receiver);
}
class ClientImpl {
:
Result Post(const std::string& path, const Headers& headers,
const char* body, size_t content_length, ContentReceiver content_receiver);
Result send_without_content_provider(
const std::string& method, const std::string& path,
const Headers& headers, const char* body, size_t content_length,
ContentReceiver content_receiver,
ContentProviderWithoutLength content_provider_without_length,
const std::string& content_type, Progress progress);
함수구현
inline Result ClientImpl::send_without_content_provider(
const std::string& method, const std::string& path, const Headers& headers,
const char* body, size_t content_length, ContentReceiver content_receiver,
ContentProviderWithoutLength content_provider_without_length,
const std::string& content_type, Progress progress) {
Request req;
req.method = method;
req.headers = headers;
req.path = path;
req.content_receiver =
[content_receiver](const char* data, size_t data_length,
uint64_t /*offset*/, uint64_t /*total_length*/) {
return content_receiver(data, data_length);
};
req.progress = progress;
auto error = Error::Success;
auto res = send_with_content_provider(
req, body, content_length, std::move(nullptr),
std::move(content_provider_without_length), content_type, error);
return Result{ std::move(res), error, std::move(req.headers) };
}
inline Result ClientImpl::Post(const std::string& path, const Headers& headers,
const char* body, size_t content_length, ContentReceiver content_receiver) {
return send_without_content_provider("POST", path, headers, body, content_length,
content_receiver, nullptr, "application/x-www-form-urlencoded", nullptr);
}
아래는 위에 구현된 POST 를 사용한 예제이다.
httplib::Headers headers = {
{ "Hello", "World!" },
:
};
std::string strPostData = "events=....";
std::string body;
auto res = cli.Post("/rest/eventSrc.json", headers, strPostData.c_str(), strPostData.size(), [&](const char* data, size_t data_length) {
body.append(data, data_length);
return true;
});