blob: e2470c2b19ac3910e58b72a6796891be85022e33 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#include "httpd.h"
#include <boost/bind.hpp>
HTTP::Server::Server(boost::asio::io_service& io_service, const tcp::endpoint& endpoint) : acceptor_(io_service, endpoint) {
start_accept();
}
void HTTP::Server::add_handler(const std::string& name, Handler handler) {
handlers[name] = handler;
}
void HTTP::Server::start_accept() {
Connection::p new_connection = Connection::p(new Connection(acceptor_.io_service()));
acceptor_.async_accept(new_connection->socket, boost::bind(&Server::handle_accept, this, new_connection, boost::asio::placeholders::error));
}
void HTTP::Server::handle_accept(Connection::p new_connection, const boost::system::error_code& error) {
if(!error) {
new_connection->read_request(boost::bind(&Server::handle_request, this, _1));
start_accept();
}
}
void HTTP::Server::handle_request(Connection::p connection) {
std::string handler;
if(connection->path.size()) {
// Pop first element of path.
handler = connection->path.front();
connection->path.erase(connection->path.begin());
} else {
handler = "index";
}
if(handlers.count(handler)) {
// Call handler.
handlers[handler](connection);
} else {
// Error 404.
}
}
|