From ac5c13620c3d3184d7026723e64b9b4ac142a7ba Mon Sep 17 00:00:00 2001 From: yhirose Date: Thu, 27 Sep 2012 20:54:54 -0400 Subject: [PATCH] Added ServerTest. --- httpsvrkit.h | 27 ++++++++++++++++++++------- test/test.cc | 17 +++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/httpsvrkit.h b/httpsvrkit.h index db4fbd4..2dd859c 100644 --- a/httpsvrkit.h +++ b/httpsvrkit.h @@ -85,6 +85,8 @@ public: void get(const char* pattern, Handler handler); void post(const char* pattern, Handler handler); + void on_ready(std::function callback); + bool run(); void stop(); @@ -94,8 +96,10 @@ private: const std::string ipaddr_or_hostname_; const int port_; socket_t sock_; - std::vector> get_handlers_; + + std::vector> get_handlers_; std::vector> post_handlers_; + std::function on_ready_; }; // Implementation @@ -242,12 +246,21 @@ inline void Server::post(const char* pattern, Handler handler) post_handlers_.push_back(std::make_pair(pattern, handler)); } +inline void Server::on_ready(std::function callback) +{ + on_ready_ = callback; +} + inline bool Server::run() { sock_ = create_server_socket(ipaddr_or_hostname_.c_str(), port_); if (sock_ == -1) { return false; } + + if (on_ready_) { + on_ready_(); + } for (;;) { socket_t fd = accept(sock_, NULL, NULL); @@ -444,14 +457,14 @@ inline void Server::process_request(FILE* fp_read, FILE* fp_write) } #define HTTP_SERVER(host, port) \ - for (std::shared_ptr svr = std::make_shared(host, port); \ - svr; \ - svr->run(), svr.reset()) + for (std::shared_ptr svr_ = std::make_shared(host, port); \ + svr_; \ + svr_->run(), svr_.reset()) #define GET(url, body) \ - svr->get(url, [&](httpsvrkit::Context& cxt) { \ - const auto& req = cxt.request; \ - auto& res = cxt.response; \ + svr_->get(url, [&](httpsvrkit::Context& cxt) { \ + const auto& req_ = cxt.request; \ + auto& res_ = cxt.response; \ body \ }); diff --git a/test/test.cc b/test/test.cc index 4d4f337..df87776 100644 --- a/test/test.cc +++ b/test/test.cc @@ -1,6 +1,7 @@ #include #include +#include using namespace std; using namespace httpsvrkit; @@ -50,4 +51,20 @@ TEST(GetHeaderValueTest, RegularValue) ASSERT_STREQ("text/html", val); } +TEST(ServerTest, GetMethod) +{ + Server svr("localhost", 1914); + + svr.get("hi", [&](httpsvrkit::Context& cxt) { + cxt.response.set_content("Hello World!"); + }); + + svr.on_ready([&]() { + // TODO: HTTP GET request... + svr.stop(); + }); + + auto f = async([&](){ svr.run(); }); +} + // vim: et ts=4 sw=4 cin cino={1s ff=unix