|
| 1 | + |
| 2 | +// Copyright 2010 Dean Michael Berris. |
| 3 | +// Distributed under the Boost Software License, Version 1.0. |
| 4 | +// (See accompanying file LICENSE_1_0.txt or copy at |
| 5 | +// http://www.boost.org/LICENSE_1_0.txt) |
| 6 | + |
| 7 | +#defineBOOST_TEST_MODULE HTTP Asynchronous Server Tests |
| 8 | + |
| 9 | +#include<vector> |
| 10 | + |
| 11 | +#include<boost/config/warning_disable.hpp> |
| 12 | +#include<boost/network/include/http/server.hpp> |
| 13 | +#include<boost/network/utils/thread_pool.hpp> |
| 14 | +#include<boost/range/algorithm/find_if.hpp> |
| 15 | + |
| 16 | +namespacenet= boost::network; |
| 17 | +namespacehttp= boost::network::http; |
| 18 | +namespaceutils= boost::network::utils; |
| 19 | + |
| 20 | +structasync_hello_world; |
| 21 | +typedef http::async_server<async_hello_world> server; |
| 22 | + |
| 23 | +structasync_hello_world { |
| 24 | + |
| 25 | +structis_content_length { |
| 26 | +template<classHeader> |
| 27 | +booloperator()(Headerconst & header) { |
| 28 | +returnboost::iequals(header.name,"content-length"); |
| 29 | + } |
| 30 | + }; |
| 31 | + |
| 32 | +voidoperator()(server::requestconst & request, server::connection_ptr connection) { |
| 33 | +static server::response_header headers[] = { |
| 34 | + {"Connection","close"} |
| 35 | + , {"Content-Type","text/plain"} |
| 36 | + , {"Server","cpp-netlib/0.9-devel"} |
| 37 | + }; |
| 38 | +if (request.method =="HEAD") { |
| 39 | + connection->set_status(server::connection::ok); |
| 40 | + connection->set_headers(boost::make_iterator_range(headers, headers+3)); |
| 41 | + }else { |
| 42 | +if (request.method =="PUT" || request.method =="POST") { |
| 43 | +static std::stringbad_request("Bad Request."); |
| 44 | + server::request::headers_container_type::iterator found = |
| 45 | +boost::find_if(request.headers,is_content_length()); |
| 46 | +if (found == request.headers.end()) { |
| 47 | + connection->set_status(server::connection::bad_request); |
| 48 | + connection->set_headers(boost::make_iterator_range(headers, headers+3)); |
| 49 | + connection->write(bad_request); |
| 50 | +return; |
| 51 | + } |
| 52 | + } |
| 53 | +staticcharconst * hello_world ="Hello, World!"; |
| 54 | + connection->set_status(server::connection::ok); |
| 55 | + connection->set_headers(boost::make_iterator_range(headers, headers+3)); |
| 56 | + std::vector<boost::asio::const_buffer> iovec; |
| 57 | + iovec.push_back(boost::asio::const_buffer(hello_world,13)); |
| 58 | + connection->write(iovec,boost::bind(&async_hello_world::error,this, _1)); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | +voiderror(boost::system::error_codeconst & ec) { |
| 63 | +// do nothing here. |
| 64 | + } |
| 65 | +}; |
| 66 | + |
| 67 | +intmain(int argc,char * argv[]) { |
| 68 | + utils::thread_poolthread_pool(2); |
| 69 | + async_hello_world handler; |
| 70 | + serverinstance("127.0.0.1","8000", handler, thread_pool); |
| 71 | + instance.run(); |
| 72 | +return0; |
| 73 | +} |
| 74 | + |