added abstraction for html parsing and response handling
This commit is contained in:
parent
11aa11903e
commit
2a4e32a274
4 changed files with 45 additions and 10 deletions
23
includes/request_parser.hpp
Normal file
23
includes/request_parser.hpp
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
#ifndef REQUEST_PARSER_HPP
|
||||
#define REQUEST_PARSER_HPP
|
||||
|
||||
#include <istream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct HttpRequest {
|
||||
string method;
|
||||
string uri;
|
||||
string version;
|
||||
map<string, string> headers;
|
||||
string body;
|
||||
};
|
||||
|
||||
class request_parser {
|
||||
public:
|
||||
HttpRequest& parse(istream& data_stream);
|
||||
};
|
||||
|
||||
#endif
|
||||
14
includes/response_handler.hpp
Normal file
14
includes/response_handler.hpp
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#ifndef RESPONSE_HANDLER_HPP
|
||||
#define RESPONSE_HANDLER_HPP
|
||||
|
||||
#include "request_parser.hpp"
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class response_handler {
|
||||
public:
|
||||
string& handle(HttpRequest request);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
@ -4,6 +4,8 @@
|
|||
#include <boost/system/detail/error_code.hpp>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "request_parser.hpp"
|
||||
#include "response_handler.hpp"
|
||||
|
||||
using namespace boost;
|
||||
using namespace std;
|
||||
|
|
@ -19,6 +21,8 @@ public:
|
|||
private:
|
||||
asio::ip::tcp::socket socket_;
|
||||
asio::streambuf buffer_;
|
||||
request_parser request_parser_;
|
||||
response_handler response_handler_;
|
||||
|
||||
explicit tcp_connection(asio::io_context& io_context);
|
||||
|
||||
|
|
|
|||
|
|
@ -27,17 +27,11 @@ void tcp_connection::handle() {
|
|||
|
||||
void tcp_connection::handle_read(const boost::system::error_code& error, size_t bytes_transferred) {
|
||||
if (!error) {
|
||||
// std::istream request_stream(&buffer_);
|
||||
// std::string request_line;
|
||||
// std::getline(request_stream, request_line);
|
||||
istream request_stream(&buffer_);
|
||||
auto requst = request_parser_.parse(request_stream);
|
||||
string response = response_handler_.handle(requst);
|
||||
|
||||
// auto parsed_data = request_parser_.parse(request_line);
|
||||
// string response = response_handler_.handle(parsed_data);
|
||||
|
||||
std::string response = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, world!";
|
||||
auto data = asio::buffer(response);
|
||||
|
||||
asio::async_write(socket_, data,
|
||||
asio::async_write(socket_, asio::buffer(response),
|
||||
bind(&tcp_connection::handle_write,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
|
|
|
|||
Reference in a new issue