#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::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if(!parse_request(buf)) { // Request parse error. 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; } return; std::istream is(&buf); HTTPRequest req(is); HTTPResponse res(socket); MusicListing::p ml = music::get(req.path); if(ml) { res.code = 200; res.status = "OK"; ml->render(req, res); } else { res.code = 404; res.status = "Not Found"; } } void print(char c) { std::cout << "Char: " << int(c) << std::endl; } bool HTTP::Connection::parse_request(boost::asio::streambuf& buf) { typedef boost::asio::buffers_iterator Iterator; Iterator begin = Iterator::begin(buf.data()); Iterator end = Iterator::end(buf.data()); qi::rule word_p = +(qi::char_ - ' ' - '\r'); qi::rule()> path_p = '/' >> +(qi::char_ - '/' - '?' - ' ') % '/'; qi::rule()> pair_p = +(qi::char_ - '=') >> '=' >> +(qi::char_ - '&' - ' '); 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)); }