From 2dcf3091edfb316f4cf296fbeb1264aea633c09f Mon Sep 17 00:00:00 2001 From: Vegard Storheil Eriksen Date: Mon, 10 Jan 2011 08:44:27 +0100 Subject: Added response_map for http response codes. --- http_connection.cpp | 21 ++++++++++++++++++--- http_connection.h | 2 +- httpd.cpp | 2 +- main.cpp | 2 +- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/http_connection.cpp b/http_connection.cpp index ff7e795..a16d237 100644 --- a/http_connection.cpp +++ b/http_connection.cpp @@ -5,8 +5,23 @@ #include #include -void HTTP::Connection::send_error(int code, std::string name) { - boost::asio::write(socket, boost::asio::buffer(boost::str(boost::format("HTTP/1.1 %1$d %2$s\r\n\r\n

%1$d %2$s

") % code % name))); +namespace response_map_init { + typedef std::pair P; + const P m[] = { + P(200, "OK"), + P(400, "Bad Request"), + P(404, "Not Found"), + P(500, "Internal Server Error"), + P(501, "Not Implemented") + }; + const P* begin = m; + const P* end = m + sizeof(m) / sizeof(P); +} + +const std::map response_map(response_map_init::begin, response_map_init::end); + +void HTTP::Connection::send_error(int code) { + boost::asio::write(socket, boost::asio::buffer(boost::str(boost::format("HTTP/1.1 %1$d %2$s\r\n\r\n

%1$d %2$s

") % code % response_map.find(code)->second))); } void HTTP::Connection::add_header(std::string key, std::string value) { @@ -47,7 +62,7 @@ void HTTP::Connection::handle_read(const boost::system::error_code& error, size_ if(!parse_request(buf)) { // Request parse error. std::cout << "Request parse error." << std::endl; - send_error(400, "Bad Request"); + send_error(400); return; } diff --git a/http_connection.h b/http_connection.h index e3a3721..d810254 100644 --- a/http_connection.h +++ b/http_connection.h @@ -44,7 +44,7 @@ namespace HTTP { std::map headers; //! Send error. - void send_error(int code, std::string name); + void send_error(int code); //! Add response header. void add_header(std::string key, std::string value); diff --git a/httpd.cpp b/httpd.cpp index 22ca999..e8d8a2c 100644 --- a/httpd.cpp +++ b/httpd.cpp @@ -29,6 +29,6 @@ void HTTP::Server::handle_request(Connection::p connection) { // Call handler. handlers[handler](connection); } else { - connection->send_error(404, "Not Found"); + connection->send_error(404); } } diff --git a/main.cpp b/main.cpp index 7f836cf..3c22d24 100644 --- a/main.cpp +++ b/main.cpp @@ -17,7 +17,7 @@ void foo_handler(HTTP::Connection::p connection) { if(ml) { ml->render(connection); } else { - connection->send_error(404, "Not Found"); + connection->send_error(404); } } -- cgit v1.2.3