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.

69 lines
2.1 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #pragma once
  2. #include <string>
  3. #include <unordered_map>
  4. #include <boost/asio/ip/tcp.hpp>
  5. #include <boost/regex.hpp>
  6. #include <boost/beast/http.hpp>
  7. namespace pEp {
  8. namespace beast = boost::beast;
  9. namespace http = beast::http;
  10. namespace net = boost::asio;
  11. using tcp = boost::asio::ip::tcp;
  12. // class Webserver
  13. //
  14. // when an URL handler is present it is called for each matching URL
  15. // otherwise this server is searching for static files in doc_root
  16. // only registered file types and no subdirectories are served for
  17. // static files
  18. //
  19. // to deliver 404 return nullptr from handler
  20. //
  21. // this server is supporting GET for static files and POST for handlers
  22. class Webserver {
  23. public:
  24. typedef boost::regex url_t;
  25. typedef http::request< http::string_body > request;
  26. typedef http::response< http::string_body > response;
  27. typedef std::function< response*(boost::cmatch, request&) > handler_t;
  28. private:
  29. struct Handling {
  30. boost::regex regex;
  31. handler_t handler;
  32. };
  33. net::io_context _ioc;
  34. tcp::acceptor _acceptor;
  35. std::string _doc_root;
  36. std::unordered_map< std::string, Handling > _urls;
  37. bool _running;
  38. std::mutex _mtx;
  39. public:
  40. Webserver(net::ip::address addr, unsigned short port, std::string doc_root);
  41. Webserver(const Webserver&) = delete;
  42. Webserver& operator=(const Webserver&) = delete;
  43. ~Webserver() { }
  44. void add_url_handler(std::string url_regex, handler_t handler);
  45. void remove_url_handler(std::string url_regex);
  46. void run();
  47. void shutdown();
  48. static beast::string_view mime_type(beast::string_view path);
  49. protected:
  50. void deliver_status(tcp::socket *socket, request req, http::status status);
  51. void deliver_file(tcp::socket *socket, request req);
  52. handler_t find_handler(request& req, boost::cmatch& m);
  53. void do_session(tcp::socket *socket);
  54. };
  55. };