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
@@ -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;
}
+4
View File
@@ -0,0 +1,4 @@
add_executable(rest_book_client main.cc)
target_link_libraries(rest_book_client webcc jsoncpp ${Boost_LIBRARIES})
target_link_libraries(rest_book_client "${CMAKE_THREAD_LIBS_INIT}")
+160
View File
@@ -0,0 +1,160 @@
#include <iostream>
#include "json/json.h"
#include "webcc/logger.h"
#include "webcc/rest_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(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;
if (!client_.Get("/books")) {
std::cout << webcc::DescribeError(client_.error()) << std::endl;
return false;
}
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::endl;
Json::Value json(Json::objectValue);
json["id"] = id;
json["title"] = title;
json["price"] = price;
if (!client_.Post("/books", JsonToString(json))) {
std::cout << webcc::DescribeError(client_.error()) << std::endl;
return false;
}
std::cout << client_.response_status() << std::endl;
return true;
}
private:
webcc::RestClient client_;
};
// -----------------------------------------------------------------------------
class BookDetailClient {
public:
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;
if (!rest_client_.Get("/book/" + id)) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
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::endl;
// NOTE: ID is already in the URL.
Json::Value json(Json::objectValue);
json["title"] = title;
json["price"] = price;
if (!rest_client_.Put("/book/" + id, JsonToString(json))) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
std::cout << rest_client_.response_status() << std::endl;
return true;
}
bool DeleteBook(const std::string& id) {
std::cout << "DeleteBook: " << id << std::endl;
if (!rest_client_.Delete("/book/" + id)) {
std::cout << webcc::DescribeError(rest_client_.error()) << std::endl;
return false;
}
std::cout << rest_client_.response_status() << std::endl;
return true;
}
private:
webcc::RestClient rest_client_;
};
// -----------------------------------------------------------------------------
void Help(const char* argv0) {
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) {
Help(argv[0]);
return 1;
}
LOG_INIT(webcc::VERB, 0);
std::string host = argv[1];
std::string port = argv[2];
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);
detail_client.GetBook("1");
detail_client.UpdateBook("1", "1Q84", 32.1);
detail_client.GetBook("1");
detail_client.DeleteBook("1");
list_client.ListBooks();
return 0;
}
+6
View File
@@ -0,0 +1,6 @@
file(GLOB SRCS *.cc *.h)
add_executable(rest_book_server ${SRCS})
target_link_libraries(rest_book_server webcc jsoncpp ${Boost_LIBRARIES})
target_link_libraries(rest_book_server "${CMAKE_THREAD_LIBS_INIT}")
+223
View File
@@ -0,0 +1,223 @@
#include "book_services.h"
#include <list>
#include <iostream>
#include "boost/lexical_cast.hpp"
#include "boost/thread/thread.hpp"
#include "json/json.h"
#include "webcc/logger.h"
// -----------------------------------------------------------------------------
// In-memory test data.
// There should be some database in a real product.
class Book {
public:
std::string id;
std::string title;
double price;
bool IsNull() const {
return id.empty();
}
Json::Value ToJson() const {
Json::Value root;
root["id"] = id;
root["title"] = title;
root["price"] = price;
return root;
}
};
std::ostream& operator<<(std::ostream& os, const Book& book) {
os << "{ " << book.id << ", " << book.title << ", " << book.price << " }";
return os;
}
static const Book kNullBook{};
class BookStore {
public:
BookStore() = default;
const std::list<Book>& books() const {
return books_;
}
const Book& GetBook(const std::string& id) const {
auto it = FindBook(id);
return (it == books_.end() ? kNullBook : *it);
}
bool AddBook(const Book& new_book) {
if (FindBook(new_book.id) == books_.end()) {
books_.push_back(new_book);
return true;
}
return false;
}
bool UpdateBook(const Book& book) {
auto it = FindBook(book.id);
if (it != books_.end()) {
it->title = book.title;
it->price = book.price;
return true;
}
return false;
}
bool DeleteBook(const std::string& id) {
auto it = FindBook(id);
if (it != books_.end()) {
books_.erase(it);
return true;
}
return false;
}
private:
std::list<Book>::const_iterator FindBook(const std::string& id) const {
return std::find_if(books_.begin(),
books_.end(),
[&id](const Book& book) { return book.id == id; });
}
std::list<Book>::iterator FindBook(const std::string& id) {
return std::find_if(books_.begin(),
books_.end(),
[&id](Book& book) { return book.id == id; });
}
private:
std::list<Book> books_;
};
static BookStore g_book_store;
// -----------------------------------------------------------------------------
static bool BookFromJson(const std::string& json, Book* book) {
Json::Value root;
Json::CharReaderBuilder builder;
std::stringstream stream(json);
std::string errs;
if (!Json::parseFromStream(builder, stream, &root, &errs)) {
std::cerr << errs << std::endl;
return false;
}
book->id = root["id"].asString();
book->title = root["title"].asString();
book->price = root["price"].asDouble();
return true;
}
// Return all books as a JSON array.
// 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());
}
Json::StreamWriterBuilder builder;
*response_content = Json::writeString(builder, root);
return true;
}
// Add a new book.
// 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;
}
// -----------------------------------------------------------------------------
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;
}
const std::string& book_id = url_sub_matches[0];
const Book& book = g_book_store.GetBook(book_id);
if (!book.IsNull()) {
Json::StreamWriterBuilder builder;
*response_content = Json::writeString(builder, book.ToJson());
return true;
}
return false;
}
// Update a book.
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;
}
const std::string& book_id = url_sub_matches[0];
Book book;
if (BookFromJson(request_content, &book)) {
book.id = book_id;
return g_book_store.UpdateBook(book);
}
return false;
}
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;
}
const std::string& book_id = url_sub_matches[0];
return g_book_store.DeleteBook(book_id);
}
+61
View File
@@ -0,0 +1,61 @@
#ifndef BOOK_SERVICES_H_
#define BOOK_SERVICES_H_
#include "webcc/rest_service.h"
// -----------------------------------------------------------------------------
// BookListService handles the HTTP GET and returns the book list based on
// query parameters specified in the URL.
// The URL should be like:
// - /books
// - /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) override;
// Create a new book.
bool Post(const std::string& request_content,
std::string* response_content) override;
private:
// Sleep for the client to test timeout control.
int sleep_seconds_ = 0;
};
// -----------------------------------------------------------------------------
// 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) override;
bool Put(const std::vector<std::string>& url_sub_matches,
const std::string& request_content,
std::string* response_content) override;
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;
}