a simple multithreaded webserver
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.9 KiB

#pragma once
#include <string>
#include <unordered_map>
#include <boost/asio/ip/tcp.hpp>
#include <boost/regex.hpp>
#include <boost/beast/http.hpp>
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
namespace pEp {
// class Webserver
// when an URL handler is present it is called for each matching URL
// otherwise this server is searching for static files in doc_root
// only registered file types and no subdirectories are served for
// static files
class Webserver {
typedef boost::regex url_t;
typedef http::request< http::string_body > request;
typedef http::response< http::string_body > response;
typedef std::function< response*(boost::cmatch, request&) > handler_t;
struct Handling {
boost::regex regex;
handler_t handler;
net::io_context _ioc;
tcp::acceptor _acceptor;
std::string _doc_root;
std::unordered_map< std::string, Handling > _urls;
bool _running;
std::mutex _mtx;
Webserver(net::ip::address addr, unsigned short port, std::string doc_root);
Webserver(const Webserver&) = delete;
Webserver& operator=(const Webserver&) = delete;
~Webserver() { }
void add_url_handler(std::string url_regex, handler_t handler);
void remove_url_handler(std::string url_regex);
void run();
void shutdown();
void deliver404(tcp::socket *socket, request req);
void deliver_file(tcp::socket *socket, request req);
handler_t find_handler(request& r, boost::cmatch& m);
void do_session(tcp::socket *socket);