#include "http_connection.h" #include "http.h" #include "music.h" #include #include #include namespace qi = boost::spirit::qi; HTTP::Connection::Connection(boost::asio::io_service& io_service) : socket(io_service) { } void HTTP::Connection::handle_write(const boost::system::error_code& error, size_t bytes_transferred) { } void HTTP::Connection::foo_handler(HTTP::Connection::p connection) { std::cout << "Handling!" << std::endl; HTTPResponse res(connection->socket); MusicListing::p ml = music::get(connection->path); if(ml) { res.code = 200; res.status = "OK"; ml->render(connection, res); } else { res.code = 404; res.status = "Not Found"; } } void HTTP::Connection::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if(!parse_request(buf)) { // Request parse error. std::cout << "Request parse error." << std::endl; //return; } std::cout << "Path: " << std::endl; for(std::vector::iterator it = path.begin(); it != path.end(); it++) { std::cout << " " << *it << std::endl; } std::cout << "Args: " << std::endl; for(std::map::iterator it = args.begin(); it != args.end(); it++) { std::cout << " " << it->first << " = " << it->second << std::endl; } std::cout << "Headers: " << std::endl; for(std::map::iterator it = headers.begin(); it != headers.end(); it++) { std::cout << " " << it->first << " = " << it->second << std::endl; } foo_handler(shared_from_this()); } void print(char c) { std::cout << "Char: " << int(c) << std::endl; } bool HTTP::Connection::parse_request(boost::asio::streambuf& buf) { std::string data(boost::asio::buffers_begin(buf.data()), boost::asio::buffers_end(buf.data())); typedef std::string::const_iterator Iterator; Iterator begin = data.begin(); Iterator end = data.end(); qi::rule word_p = +(qi::char_ - ' ' - '\r'); qi::rule urlchar_p = (qi::char_ - '%') | ('%' >> qi::uint_parser()); qi::rule()> path_p = '/' >> +(urlchar_p - '/' - '?' - ' ') % '/'; qi::rule()> pair_p = +(urlchar_p - '=') >> '=' >> +(urlchar_p - '&' - ' '); qi::rule()> args_p = '?' >> pair_p >> *('&' >> pair_p); qi::rule()> header_p = +(qi::char_ - ':') >> ": " >> +(qi::char_ - '\r'); qi::rule()> headers_p = *(header_p >> "\r\n"); return qi::parse(begin, end, // Method, path, args, version: word_p >> ' ' >> path_p >> -args_p >> ' ' >> word_p >> "\r\n" >> // Headers: headers_p >> // End of headers: "\r\n", // Store into: method, path, args, version, headers); } void HTTP::Connection::start() { boost::asio::async_read_until(socket, buf, "\r\n\r\n", boost::bind(&Connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); }