Add async-client support; refine http message dump format.

This commit is contained in:
Adam Gu
2018-06-04 12:03:22 +08:00
parent 79665c75ba
commit 9bf45e6ecb
48 changed files with 798 additions and 402 deletions
+4
View File
@@ -0,0 +1,4 @@
add_executable(http_async_client main.cc)
target_link_libraries(http_async_client webcc ${Boost_LIBRARIES})
target_link_libraries(http_async_client "${CMAKE_THREAD_LIBS_INIT}")
+49
View File
@@ -0,0 +1,49 @@
#include <iostream>
#include "boost/asio/io_context.hpp"
#include "webcc/logger.h"
#include "webcc/http_async_client.h"
// In order to test this client, create a file index.html whose content is
// simply "Hello, World!", then start a HTTP server with Python 3:
// $ python -m http.server
// The default port number should be 8000.
void Test(boost::asio::io_context& ioc) {
std::shared_ptr<webcc::HttpRequest> request(new webcc::HttpRequest());
request->set_method(webcc::kHttpGet);
request->set_url("/index.html");
request->SetHost("localhost", "8000");
request->Build();
webcc::HttpAsyncClientPtr client(new webcc::HttpAsyncClient(ioc));
// Response handler.
auto handler = [](std::shared_ptr<webcc::HttpResponse> response,
webcc::Error error) {
if (error == webcc::kNoError) {
std::cout << response->content() << std::endl;
} else {
std::cout << webcc::DescribeError(error) << std::endl;
}
};
client->Request(request, handler);
}
int main() {
LOG_INIT(webcc::ERRO, 0);
boost::asio::io_context ioc;
Test(ioc);
Test(ioc);
Test(ioc);
ioc.run();
return 0;
}
+4
View File
@@ -0,0 +1,4 @@
add_executable(http_client main.cc)
target_link_libraries(http_client webcc ${Boost_LIBRARIES})
target_link_libraries(http_client "${CMAKE_THREAD_LIBS_INIT}")
+38
View File
@@ -0,0 +1,38 @@
#include <iostream>
#include "webcc/logger.h"
#include "webcc/http_client.h"
// In order to test this client, create a file index.html whose content is
// simply "Hello, World!", then start a HTTP server with Python 3:
// $ python -m http.server
// The default port number should be 8000.
void Test() {
webcc::HttpRequest request;
request.set_method(webcc::kHttpGet);
request.set_url("/index.html");
request.SetHost("localhost", "8000");
request.Build();
webcc::HttpResponse response;
webcc::HttpClient client;
if (!client.Request(request)) {
return;
}
std::cout << response.content() << std::endl;
}
int main() {
LOG_INIT(webcc::ERRO, 0);
Test();
Test();
Test();
return 0;
}
@@ -0,0 +1,4 @@
add_executable(rest_book_async_client main.cc)
target_link_libraries(rest_book_async_client webcc jsoncpp ${Boost_LIBRARIES})
target_link_libraries(rest_book_async_client "${CMAKE_THREAD_LIBS_INIT}")
+137
View File
@@ -0,0 +1,137 @@
#include <iostream>
#include "json/json.h"
#include "webcc/logger.h"
#include "webcc/rest_async_client.h"
// -----------------------------------------------------------------------------
// Write a JSON object to string.
std::string JsonToString(const Json::Value& json) {
Json::StreamWriterBuilder builder;
return Json::writeString(builder, json);
}
// -----------------------------------------------------------------------------
class BookListClient {
public:
BookListClient(boost::asio::io_context& io_context,
const std::string& host, const std::string& port)
: client_(io_context, host, port) {
}
void ListBooks(webcc::HttpResponseHandler handler) {
std::cout << "ListBooks" << std::endl;
client_.Get("/books", handler);
}
void CreateBook(const std::string& id,
const std::string& title,
double price,
webcc::HttpResponseHandler handler) {
std::cout << "CreateBook: " << id << " " << title << " " << price
<< std::endl;
Json::Value json(Json::objectValue);
json["id"] = id;
json["title"] = title;
json["price"] = price;
client_.Post("/books", JsonToString(json), handler);
}
private:
webcc::RestAsyncClient client_;
};
// -----------------------------------------------------------------------------
class BookDetailClient {
public:
BookDetailClient(boost::asio::io_context& io_context,
const std::string& host, const std::string& port)
: rest_client_(io_context, host, port) {
}
void GetBook(const std::string& id, webcc::HttpResponseHandler handler) {
std::cout << "GetBook: " << id << std::endl;
rest_client_.Get("/book/" + id, handler);
}
void UpdateBook(const std::string& id,
const std::string& title,
double price,
webcc::HttpResponseHandler handler) {
std::cout << "UpdateBook: " << id << " " << title << " " << price
<< std::endl;
// NOTE: ID is already in the URL.
Json::Value json(Json::objectValue);
json["title"] = title;
json["price"] = price;
rest_client_.Put("/book/" + id, JsonToString(json), handler);
}
void DeleteBook(const std::string& id, webcc::HttpResponseHandler handler) {
std::cout << "DeleteBook: " << id << std::endl;
rest_client_.Delete("/book/" + id, handler);
}
private:
webcc::RestAsyncClient rest_client_;
};
// -----------------------------------------------------------------------------
void Help(const char* argv0) {
std::cout << "Usage: " << argv0 << " <host> <port>" << std::endl;
std::cout << " E.g.," << std::endl;
std::cout << " " << argv0 << " localhost 8080" << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
Help(argv[0]);
return 1;
}
LOG_INIT(webcc::ERRO, 0);
std::string host = argv[1];
std::string port = argv[2];
boost::asio::io_context io_context;
BookListClient list_client(io_context, host, port);
BookDetailClient detail_client(io_context, host, port);
// Response handler.
auto handler = [](std::shared_ptr<webcc::HttpResponse> response,
webcc::Error error) {
if (error == webcc::kNoError) {
std::cout << response->content() << std::endl;
} else {
std::cout << webcc::DescribeError(error) << std::endl;
}
};
list_client.ListBooks(handler);
list_client.CreateBook("1", "1984", 12.3, handler);
detail_client.GetBook("1", handler);
detail_client.UpdateBook("1", "1Q84", 32.1, handler);
detail_client.GetBook("1", handler);
detail_client.DeleteBook("1", handler);
list_client.ListBooks(handler);
io_context.run();
return 0;
}
@@ -1,12 +1,8 @@
#include <iostream>
#include "boost/algorithm/string.hpp"
#include "json/json.h"
#include "webcc/logger.h"
#include "webcc/http_client.h"
#include "webcc/http_request.h"
#include "webcc/http_response.h"
#include "webcc/rest_client.h"
// -----------------------------------------------------------------------------
@@ -21,26 +17,28 @@ std::string JsonToString(const Json::Value& json) {
class BookListClient {
public:
BookListClient(const std::string& host, const std::string& port)
: rest_client_(host, port) {
BookListClient(const std::string& host, const std::string& port,
int timeout_seconds)
: client_(host, port) {
client_.set_timeout_seconds(timeout_seconds);
}
bool ListBooks() {
std::cout << "ListBooks" << std::endl;
webcc::HttpResponse http_response;
if (!rest_client_.Get("/books", &http_response)) {
if (!client_.Get("/books")) {
std::cout << webcc::DescribeError(client_.error()) << std::endl;
return false;
}
std::cout << http_response.content() << std::endl;
std::cout << client_.response_content() << std::endl;
return true;
}
bool CreateBook(const std::string& id,
const std::string& title,
double price) {
std::cout << "CreateBook: " << id << " " << title << " " << price
std::cout << "CreateBook: " << id << ", " << title << ", " << price
<< std::endl;
Json::Value json(Json::objectValue);
@@ -48,44 +46,46 @@ public:
json["title"] = title;
json["price"] = price;
webcc::HttpResponse http_response;
if (!rest_client_.Post("/books", JsonToString(json), &http_response)) {
if (!client_.Post("/books", JsonToString(json))) {
std::cout << webcc::DescribeError(client_.error()) << std::endl;
return false;
}
std::cout << http_response.status() << std::endl;
std::cout << client_.response_status() << std::endl;
return true;
}
private:
webcc::RestClient rest_client_;
webcc::RestClient client_;
};
// -----------------------------------------------------------------------------
class BookDetailClient {
public:
BookDetailClient(const std::string& host, const std::string& port)
BookDetailClient(const std::string& host, const std::string& port,
int timeout_seconds)
: rest_client_(host, port) {
rest_client_.set_timeout_seconds(timeout_seconds);
}
bool GetBook(const std::string& id) {
std::cout << "GetBook: " << id << std::endl;
webcc::HttpResponse http_response;
if (!rest_client_.Get("/book/" + id, &http_response)) {
if (!rest_client_.Get("/book/" + id)) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
std::cout << http_response.content() << std::endl;
std::cout << rest_client_.response_content() << std::endl;
return true;
}
bool UpdateBook(const std::string& id,
const std::string& title,
double price) {
std::cout << "UpdateBook: " << id << " " << title << " " << price
std::cout << "UpdateBook: " << id << ", " << title << ", " << price
<< std::endl;
// NOTE: ID is already in the URL.
@@ -93,24 +93,24 @@ public:
json["title"] = title;
json["price"] = price;
webcc::HttpResponse http_response;
if (!rest_client_.Put("/book/" + id, JsonToString(json), &http_response)) {
if (!rest_client_.Put("/book/" + id, JsonToString(json))) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
std::cout << http_response.status() << std::endl;
std::cout << rest_client_.response_status() << std::endl;
return true;
}
bool DeleteBook(const std::string& id) {
std::cout << "DeleteBook: " << id << std::endl;
webcc::HttpResponse http_response;
if (!rest_client_.Delete("/book/" + id, &http_response)) {
if (!rest_client_.Delete("/book/" + id)) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
std::cout << http_response.status() << std::endl;
std::cout << rest_client_.response_status() << std::endl;
return true;
}
@@ -121,24 +121,30 @@ private:
// -----------------------------------------------------------------------------
void Help(const char* argv0) {
std::cout << "Usage: " << argv0 << " <host> <port>" << std::endl;
std::cout << "Usage: " << argv0 << " <host> <port> [timeout]" << std::endl;
std::cout << " E.g.," << std::endl;
std::cout << " " << argv0 << " localhost 8080" << std::endl;
std::cout << " " << argv0 << " localhost 8080 2" << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
if (argc < 3) {
Help(argv[0]);
return 1;
}
LOG_INIT(webcc::ERRO, 0);
LOG_INIT(webcc::VERB, 0);
std::string host = argv[1];
std::string port = argv[2];
BookListClient list_client(host, port);
BookDetailClient detail_client(host, port);
int timeout_seconds = -1;
if (argc > 3) {
timeout_seconds = std::atoi(argv[3]);
}
BookListClient list_client(host, port, timeout_seconds);
BookDetailClient detail_client(host, port, timeout_seconds);
list_client.ListBooks();
list_client.CreateBook("1", "1984", 12.3);
@@ -4,7 +4,9 @@
#include <iostream>
#include "boost/lexical_cast.hpp"
#include "boost/thread/thread.hpp"
#include "json/json.h"
#include "webcc/logger.h"
// -----------------------------------------------------------------------------
@@ -121,6 +123,11 @@ static bool BookFromJson(const std::string& json, Book* book) {
// TODO: Support query parameters.
bool BookListService::Get(const webcc::UrlQuery& /* query */,
std::string* response_content) {
if (sleep_seconds_ > 0) {
LOG_INFO("Sleep %d seconds...", sleep_seconds_);
boost::this_thread::sleep_for(boost::chrono::seconds(sleep_seconds_));
}
Json::Value root(Json::arrayValue);
for (const Book& book : g_book_store.books()) {
root.append(book.ToJson());
@@ -136,10 +143,16 @@ bool BookListService::Get(const webcc::UrlQuery& /* query */,
// No response content.
bool BookListService::Post(const std::string& request_content,
std::string* /* response_content */) {
if (sleep_seconds_ > 0) {
LOG_INFO("Sleep %d seconds...", sleep_seconds_);
boost::this_thread::sleep_for(boost::chrono::seconds(sleep_seconds_));
}
Book book;
if (BookFromJson(request_content, &book)) {
return g_book_store.AddBook(book);
}
return false;
}
@@ -148,6 +161,11 @@ bool BookListService::Post(const std::string& request_content,
bool BookDetailService::Get(const std::vector<std::string>& url_sub_matches,
const webcc::UrlQuery& query,
std::string* response_content) {
if (sleep_seconds_ > 0) {
LOG_INFO("Sleep %d seconds...", sleep_seconds_);
boost::this_thread::sleep_for(boost::chrono::seconds(sleep_seconds_));
}
if (url_sub_matches.size() != 1) {
return false;
}
@@ -168,6 +186,11 @@ bool BookDetailService::Get(const std::vector<std::string>& url_sub_matches,
bool BookDetailService::Put(const std::vector<std::string>& url_sub_matches,
const std::string& request_content,
std::string* response_content) {
if (sleep_seconds_ > 0) {
LOG_INFO("Sleep %d seconds...", sleep_seconds_);
boost::this_thread::sleep_for(boost::chrono::seconds(sleep_seconds_));
}
if (url_sub_matches.size() != 1) {
return false;
}
@@ -185,6 +208,11 @@ bool BookDetailService::Put(const std::vector<std::string>& url_sub_matches,
bool BookDetailService::Delete(
const std::vector<std::string>& url_sub_matches) {
if (sleep_seconds_ > 0) {
LOG_INFO("Sleep %d seconds...", sleep_seconds_);
boost::this_thread::sleep_for(boost::chrono::seconds(sleep_seconds_));
}
if (url_sub_matches.size() != 1) {
return false;
}
@@ -12,17 +12,25 @@
// - /books?name={BookName}
// The query parameters could be regular expressions.
class BookListService : public webcc::RestListService {
public:
BookListService(int sleep_seconds) : sleep_seconds_(sleep_seconds) {
}
protected:
// Return a list of books based on query parameters.
// URL examples:
// - /books
// - /books?name={BookName}
bool Get(const webcc::UrlQuery& query,
std::string* response_content) final;
std::string* response_content) override;
// Create a new book.
bool Post(const std::string& request_content,
std::string* response_content) final;
std::string* response_content) override;
private:
// Sleep for the client to test timeout control.
int sleep_seconds_ = 0;
};
// -----------------------------------------------------------------------------
@@ -30,16 +38,24 @@ class BookListService : public webcc::RestListService {
// The URL is like '/books/{BookID}', and the 'url_sub_matches' parameter
// contains the matched book ID.
class BookDetailService : public webcc::RestDetailService {
public:
BookDetailService(int sleep_seconds) : sleep_seconds_(sleep_seconds) {
}
protected:
bool Get(const std::vector<std::string>& url_sub_matches,
const webcc::UrlQuery& query,
std::string* response_content) final;
std::string* response_content) override;
bool Put(const std::vector<std::string>& url_sub_matches,
const std::string& request_content,
std::string* response_content) final;
std::string* response_content) override;
bool Delete(const std::vector<std::string>& url_sub_matches) final;
bool Delete(const std::vector<std::string>& url_sub_matches) override;
private:
// Sleep for the client to test timeout control.
int sleep_seconds_ = 0;
};
#endif // BOOK_SERVICE_H_
+52
View File
@@ -0,0 +1,52 @@
#include <iostream>
#include "webcc/logger.h"
#include "webcc/rest_server.h"
#include "book_services.h"
void Help(const char* argv0) {
std::cout << "Usage: " << argv0 << " <port> [seconds]" << std::endl;
std::cout << "If |seconds| is provided, the server will sleep these seconds "
"before sending back each response."
<< std::endl;
std::cout << " E.g.," << std::endl;
std::cout << " " << argv0 << " 8080" << std::endl;
std::cout << " " << argv0 << " 8080 3" << std::endl;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
Help(argv[0]);
return 1;
}
LOG_INIT(webcc::VERB, 0);
unsigned short port = std::atoi(argv[1]);
int sleep_seconds = 0;
if (argc >= 3) {
sleep_seconds = std::atoi(argv[2]);
}
std::size_t workers = 2;
try {
webcc::RestServer server(port, workers);
server.Bind(std::make_shared<BookListService>(sleep_seconds),
"/books", false);
server.Bind(std::make_shared<BookDetailService>(sleep_seconds),
"/book/(\\d+)", true);
server.Run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
-41
View File
@@ -1,41 +0,0 @@
#include <iostream>
#include "webcc/logger.h"
#include "webcc/rest_server.h"
#include "book_services.h"
static void Help(const char* argv0) {
std::cout << "Usage: " << argv0 << " <port>" << std::endl;
std::cout << " E.g.," << std::endl;
std::cout << " " << argv0 << " 8080" << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
Help(argv[0]);
return 1;
}
LOG_INIT(webcc::VERB, 0);
unsigned short port = std::atoi(argv[1]);
std::size_t workers = 2;
try {
webcc::RestServer server(port, workers);
server.Bind(std::make_shared<BookListService>(), "/books", false);
server.Bind(std::make_shared<BookDetailService>(), "/book/(\\d+)", true);
server.Run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
@@ -1,7 +1,3 @@
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
file(GLOB SRCS *.cc *.h)
add_executable(soap_calc_client ${SRCS})
@@ -74,7 +74,7 @@ bool CalcClient::Calc(const std::string& operation,
if (error != webcc::kNoError) {
LOG_ERRO("Operation '%s' failed: %s",
operation.c_str(),
webcc::GetErrorMessage(error));
webcc::DescribeError(error));
return false;
}
@@ -1,7 +1,3 @@
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
file(GLOB SRCS *.cc *.h)
add_executable(soap_calc_server ${SRCS})
@@ -1,6 +1,8 @@
#include <iostream>
#include "webcc/logger.h"
#include "webcc/soap_server.h"
#include "calc_service.h"
static void Help(const char* argv0) {