#include "httpd.h" #include "music.h" #include "http.h" #include #include #include #include #include #include HTTPConnection::HTTPConnection(boost::asio::io_service& io_service) : socket(io_service) { } void HTTPConnection::handle_write(const boost::system::error_code& error, size_t bytes_transferred) { } void HTTPConnection::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { std::istream is(&buf); HTTPRequest req(is); HTTPResponse res(socket); MusicListing *ml = music::find(req.path); if(ml) { res.code = 200; res.status = "OK"; ml->render(req, res); } else { res.code = 404; res.status = "Not Found"; } } HTTPConnection::pointer HTTPConnection::create(boost::asio::io_service& io_service) { return pointer(new HTTPConnection(io_service)); } void HTTPConnection::start() { boost::asio::async_read_until(socket, buf, "\r\n\r\n", boost::bind(&HTTPConnection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } HTTPServer::HTTPServer(boost::asio::io_service& io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 8000)) { start_accept(); } void HTTPServer::start_accept() { HTTPConnection::pointer new_connection = HTTPConnection::create(acceptor_.io_service()); acceptor_.async_accept(new_connection->socket, boost::bind(&HTTPServer::handle_accept, this, new_connection, boost::asio::placeholders::error)); } void HTTPServer::handle_accept(HTTPConnection::pointer new_connection, const boost::system::error_code& error) { if(!error) { new_connection->start(); start_accept(); } }