Crow/include/http_response.h

92 lines
2.3 KiB
C
Raw Normal View History

2014-04-01 12:25:16 +00:00
#pragma once
#include <string>
#include <unordered_map>
2014-04-17 14:06:41 +00:00
#include "json.h"
2014-04-01 12:25:16 +00:00
2014-04-26 17:19:59 +00:00
namespace crow
2014-04-01 12:25:16 +00:00
{
2014-09-06 19:30:53 +00:00
template <typename Handler, typename ... Middlewares>
class Connection;
2014-04-01 12:25:16 +00:00
struct response
{
2014-09-06 19:30:53 +00:00
template <typename Handler, typename ... Middlewares>
friend class crow::Connection;
2014-04-01 12:25:16 +00:00
std::string body;
2014-04-17 14:06:41 +00:00
json::wvalue json_value;
int code{200};
2014-04-01 12:25:16 +00:00
std::unordered_map<std::string, std::string> headers;
2014-04-01 12:25:16 +00:00
response() {}
explicit response(int code) : code(code) {}
response(std::string body) : body(std::move(body)) {}
2014-04-17 14:06:41 +00:00
response(json::wvalue&& json_value) : json_value(std::move(json_value)) {}
2014-04-18 22:12:56 +00:00
response(const json::wvalue& json_value) : body(json::dump(json_value)) {}
response(int code, std::string body) : body(std::move(body)), code(code) {}
2014-04-17 14:06:41 +00:00
response(response&& r)
{
*this = std::move(r);
}
response& operator = (const response& r) = delete;
2014-09-06 19:30:53 +00:00
response& operator = (response&& r) noexcept
2014-04-17 14:06:41 +00:00
{
body = std::move(r.body);
json_value = std::move(r.json_value);
code = r.code;
headers = std::move(r.headers);
completed_ = r.completed_;
2014-04-17 14:06:41 +00:00
return *this;
}
2014-09-06 19:30:53 +00:00
bool is_completed() const noexcept
{
return completed_;
}
void clear()
{
body.clear();
json_value.clear();
code = 200;
headers.clear();
completed_ = false;
}
void write(const std::string& body_part)
{
body += body_part;
}
void end()
{
if (!completed_)
{
if (complete_request_handler_)
{
complete_request_handler_();
}
2014-09-06 19:30:53 +00:00
completed_ = true;
}
}
void end(const std::string& body_part)
{
body += body_part;
end();
}
2014-08-06 16:18:33 +00:00
bool is_alive()
{
return is_alive_helper_ && is_alive_helper_();
}
private:
bool completed_{};
std::function<void()> complete_request_handler_;
2014-08-06 16:18:33 +00:00
std::function<bool()> is_alive_helper_;
2014-04-01 12:25:16 +00:00
};
}