diff --git a/webserver.cc b/webserver.cc index 9c6d42e..ed96375 100644 --- a/webserver.cc +++ b/webserver.cc @@ -61,11 +61,20 @@ void Webserver::remove_url_handler(std::string url_regex) { _urls.erase(url_regex); } +void Webserver::deliver405(tcp::socket *socket, Webserver::request req) +{ + http::response< http::string_body > res{http::status::method_not_allowed, req.version()}; + res.set(http::field::content_type, "text/html"); + res.body() = "404 not found"; + res.keep_alive(req.keep_alive()); + res.prepare_payload(); +} + void Webserver::deliver404(tcp::socket *socket, Webserver::request req) { http::response< http::string_body > res{http::status::not_found, req.version()}; res.set(http::field::content_type, "text/html"); - res.body() = "404 file not found"; + res.body() = "404 not found"; res.keep_alive(req.keep_alive()); res.prepare_payload(); } @@ -111,28 +120,40 @@ void Webserver::do_session(tcp::socket *socket) return fail(ec, "reading from stream"); } - boost::cmatch m; - Webserver::response *res = nullptr; - Webserver::handler_t handler = find_handler(req, m); - - if (handler) { - res = handler(m, req); - if (res) { - res->prepare_payload(); - http::write(*socket, *res, ec); - delete res; - if (ec) { - delete socket; - return fail(ec, "writing to stream"); + switch (req.method()) { + case http::verb::post: { + boost::cmatch m; + Webserver::response *res = nullptr; + Webserver::handler_t handler = find_handler(req, m); + + if (handler) { + res = handler(m, req); + if (res) { + res->prepare_payload(); + http::write(*socket, *res, ec); + delete res; + if (ec) { + delete socket; + return fail(ec, "writing to stream"); + } + } + else { + deliver404(socket, req); + } + } + else { + deliver404(socket, req); } } - else { - deliver404(socket, req); - } - } - else { - deliver_file(socket, req); - } + break; + + case http::verb::get: + deliver_file(socket, req); + break; + + default: + deliver405(socket, req); + }; } socket->shutdown(tcp::socket::shutdown_send, ec); diff --git a/webserver.hh b/webserver.hh index 8010f14..7914641 100644 --- a/webserver.hh +++ b/webserver.hh @@ -18,6 +18,10 @@ namespace pEp { // 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: @@ -53,6 +57,7 @@ namespace pEp { protected: void deliver404(tcp::socket *socket, request req); + void deliver405(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);