Files
spark/src/lib/config/tests/HTTPServer.cpp
T
John Colvin a82932652b fix build: Copy a handful of files over from spark_crypto.dev
This fixes the last of the boost-related errors
2022-09-28 19:49:17 -04:00

100 lines
2.6 KiB
C++
Executable File

#include "HTTPServer.h"
#include "lib/utils/bts_assert.h"
using boost::asio::ip::tcp;
namespace bts {
namespace config {
namespace internal {
HTTPServer::HTTPServer()
: _io_service(),
_acceptor(
_io_service,
tcp::endpoint(boost::asio::ip::address_v4::loopback(), 0)),
_cur_socket(), _request_response_pairs(), _thread(), _done(false) {}
unsigned int HTTPServer::port() const {
return _acceptor.local_endpoint().port();
}
void HTTPServer::add_response(
const std::string &path,
const std::string &response,
const std::string &content) {
_request_response_pairs[path] = response + content;
}
void HTTPServer::start() {
_thread.reset(new boost::thread(boost::bind(&HTTPServer::worker, this)));
}
void HTTPServer::stop() {
_done = true;
_io_service.stop();
if (_thread) {
_thread->join();
_thread.reset();
}
}
void HTTPServer::worker() {
start_accept();
_io_service.run();
}
void HTTPServer::start_accept() {
_cur_socket.reset(new boost::asio::ip::tcp::socket(_io_service));
_acceptor.async_accept(
*_cur_socket.get(),
boost::bind(
&HTTPServer::handle_accept, this, _cur_socket.get(),
boost::asio::placeholders::error));
}
void HTTPServer::handle_accept(
boost::asio::ip::tcp::socket *socket,
const boost::system::error_code &error) {
if (!error) {
handle_connect(socket);
}
start_accept();
}
void HTTPServer::handle_connect(boost::asio::ip::tcp::socket *socket) {
boost::asio::streambuf buffer;
size_t size = boost::asio::read_until(*socket, buffer, "\r\n\r\n");
std::string request(size, 0);
buffer.sgetn(&request[0], size);
size_t start = request.find("GET ") + 4;
size_t end = request.find(" HTTP/1.1\r\n");
size_t url_args = request.find("?");
if (url_args != std::string::npos)
end = std::min(end, url_args);
std::string request_path = request.substr(start, end - start);
std::map<std::string, std::string>::iterator request_match =
_request_response_pairs.find(request_path);
if (request_match == _request_response_pairs.end()) {
std::string response = "HTTP/1.0 404 NOT FOUND\r\n"
"Content-Type: text/plain\r\n\r\n"
"not found\r\n";
boost::asio::write(*socket, boost::asio::buffer(response));
} else {
boost::asio::write(*socket, boost::asio::buffer(request_match->second));
}
boost::system::error_code ec;
socket->shutdown(tcp::socket::shutdown_both, ec);
socket->close(ec);
}
} // namespace internal
} // namespace config
} // namespace bts