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.
 
 
 

67 lines
2.1 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
//
// to deliver 404 return nullptr from handler
//
// this server is supporting GET for static files and POST for handlers
class Webserver {
public:
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;
private:
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;
public:
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();
static beast::string_view mime_type(beast::string_view path);
protected:
void deliver_status(tcp::socket *socket, request req, http::status status);
void deliver_file(tcp::socket *socket, request req);
handler_t find_handler(request& req, boost::cmatch& m);
void do_session(tcp::socket *socket);
};
};