netlib で HTTP Server を書いてみた
Boost.Asio だけだとしんどそうだったので netlib でちょっと書いてみました。
[環境]
- netlib 0.9.5
- Boost 1.53.0
- Visual Studio 2010
[ソース]
#include <boost/network/include/http/server.hpp> struct hello_world{ typedef boost::network::http::server<hello_world> server; void operator ()(server::request const &request, server::response &response){ namespace http = boost::network::http; typedef server::string_type string; string ip = http::source(request); string path = destination(request); std::ostringstream data; data << "Hello HTTP Server World!" << "<br/>"; data << "Your Address is" << ip << "<br/>"; data << "Request Path is " << path << "<br/>"; response = server::response::stock_reply( server::response::ok, data.str() ); } void log(...){ } }; int main(){ typedef hello_world::server server; auto address = "localhost"; auto port = "8000"; try{ hello_world handler; server::options options(handler); server server_(options.address(address).port(port)); server_.run(); } catch(std::exception& e){ std::cout << e.what() << std::endl; return 1; } return 0; }
[ http://localhost:8000/homu/mami ]
Hello HTTP Server World! Your Address is127.0.0.1 Request Path is /homu/mami
上記のコードをコンパイルして実行させて http://localhost:8000/homu/mami にアクセスすると設定した値が出力されます。
かなり簡素なコードなのでわかりやすいですね。
ちなみに Boost.Asio の Example にも似たようなコードが載っているので Boost オンリーで行いたい場合はそれを参考にするのがいいと思います。