Refine timeout control; refine rest book examples.

This commit is contained in:
Adam Gu
2018-08-23 17:28:02 +08:00
parent 2e2b45dd43
commit e9096d4e53
16 changed files with 313 additions and 201 deletions
+52
View File
@@ -0,0 +1,52 @@
#include "example/common/book_json.h"
#include <sstream>
#include <iostream>
#include "json/json.h"
#include "example/common/book.h"
std::string JsonToString(const Json::Value& json) {
Json::StreamWriterBuilder builder;
return Json::writeString(builder, json);
}
Json::Value StringToJson(const std::string& str) {
Json::Value json;
Json::CharReaderBuilder builder;
std::stringstream stream(str);
std::string errs;
if (!Json::parseFromStream(builder, stream, &json, &errs)) {
std::cerr << errs << std::endl;
}
return json;
}
Json::Value BookToJson(const Book& book) {
Json::Value root;
root["id"] = book.id;
root["title"] = book.title;
root["price"] = book.price;
return root;
}
std::string BookToJsonString(const Book& book) {
return JsonToString(BookToJson(book));
}
bool JsonStringToBook(const std::string& json_str, Book* book) {
Json::Value json = StringToJson(json_str);
if (!json) {
return false;
}
book->id = json["id"].asString();
book->title = json["title"].asString();
book->price = json["price"].asDouble();
return true;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef EXAMPLE_COMMON_BOOK_JSON_H_
#define EXAMPLE_COMMON_BOOK_JSON_H_
#include <string>
#include "json/json-forwards.h"
struct Book;
std::string JsonToString(const Json::Value& json);
Json::Value StringToJson(const std::string& str);
Json::Value BookToJson(const Book& book);
std::string BookToJsonString(const Book& book);
bool JsonStringToBook(const std::string& json_str, Book* book);
#endif // EXAMPLE_COMMON_BOOK_JSON_H_
+12 -3
View File
@@ -1,4 +1,13 @@
add_executable(rest_book_async_client main.cc)
set(TARGET_NAME rest_book_async_client)
target_link_libraries(rest_book_async_client webcc jsoncpp ${Boost_LIBRARIES})
target_link_libraries(rest_book_async_client "${CMAKE_THREAD_LIBS_INIT}")
set(SRCS
../common/book.cc
../common/book.h
../common/book_json.cc
../common/book_json.h
main.cc)
add_executable(${TARGET_NAME} ${SRCS})
target_link_libraries(${TARGET_NAME} webcc jsoncpp ${Boost_LIBRARIES})
target_link_libraries(${TARGET_NAME} "${CMAKE_THREAD_LIBS_INIT}")
+105 -34
View File
@@ -8,18 +8,72 @@
// -----------------------------------------------------------------------------
// Write a JSON object to string.
std::string JsonToString(const Json::Value& json) {
static std::string JsonToString(const Json::Value& json) {
Json::StreamWriterBuilder builder;
return Json::writeString(builder, json);
}
static Json::Value StringToJson(const std::string& str) {
Json::Value json;
Json::CharReaderBuilder builder;
std::stringstream stream(str);
std::string errs;
if (!Json::parseFromStream(builder, stream, &json, &errs)) {
std::cerr << errs << std::endl;
}
return json;
}
// -----------------------------------------------------------------------------
class BookListClient {
class BookClientBase {
public:
BookClientBase(boost::asio::io_context& io_context,
const std::string& host, const std::string& port,
int timeout_seconds)
: rest_client_(io_context, host, port) {
rest_client_.set_timeout_seconds(timeout_seconds);
}
virtual ~BookClientBase() = default;
protected:
void PrintSeparateLine() {
std::cout << "--------------------------------";
std::cout << "--------------------------------";
std::cout << std::endl;
}
// Generic response handler for RestAsyncClient APIs.
void GenericHandler(std::function<void(webcc::HttpResponsePtr)> rsp_callback,
webcc::HttpResponsePtr response,
webcc::Error error,
bool timed_out) {
if (error != webcc::kNoError) {
std::cout << webcc::DescribeError(error);
if (timed_out) {
std::cout << " (timed out)";
}
std::cout << std::endl;
} else {
// Call the response callback on success.
rsp_callback(response);
}
}
webcc::RestAsyncClient rest_client_;
};
// -----------------------------------------------------------------------------
class BookListClient : public BookClientBase {
public:
BookListClient(boost::asio::io_context& io_context,
const std::string& host, const std::string& port)
: rest_client_(io_context, host, port) {
const std::string& host, const std::string& port,
int timeout_seconds)
: BookClientBase(io_context, host, port, timeout_seconds) {
}
void ListBooks(webcc::HttpResponseHandler handler) {
@@ -28,38 +82,48 @@ class BookListClient {
rest_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;
void CreateBook(const std::string& title, double price,
std::function<void(std::string)> id_callback) {
std::cout << "CreateBook: " << title << " " << price << std::endl;
Json::Value json(Json::objectValue);
json["id"] = id;
json["title"] = title;
json["price"] = price;
rest_client_.Post("/books", JsonToString(json), handler);
}
auto rsp_callback = [id_callback](webcc::HttpResponsePtr response) {
Json::Value rsp_json = StringToJson(response->content());
id_callback(rsp_json["id"].asString());
};
private:
webcc::RestAsyncClient rest_client_;
rest_client_.Post("/books", JsonToString(json),
std::bind(&BookListClient::GenericHandler, this,
rsp_callback,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3));
}
};
// -----------------------------------------------------------------------------
class BookDetailClient {
class BookDetailClient : public BookClientBase {
public:
BookDetailClient(boost::asio::io_context& io_context,
const std::string& host, const std::string& port)
: rest_client_(io_context, host, port) {
const std::string& host, const std::string& port,
int timeout_seconds)
: BookClientBase(io_context, host, port, timeout_seconds) {
}
void GetBook(const std::string& id, webcc::HttpResponseHandler handler) {
std::cout << "GetBook: " << id << std::endl;
rest_client_.Get("/book/" + id, handler);
auto rsp_callback = [](webcc::HttpResponsePtr response) {
Json::Value rsp_json = StringToJson(response->content());
//id_callback(rsp_json["id"].asString());
};
rest_client_.Get("/books/" + id, handler);
}
void UpdateBook(const std::string& id,
@@ -74,29 +138,27 @@ class BookDetailClient {
json["title"] = title;
json["price"] = price;
rest_client_.Put("/book/" + id, JsonToString(json), handler);
rest_client_.Put("/books/" + 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);
rest_client_.Delete("/books/" + id, handler);
}
private:
webcc::RestAsyncClient rest_client_;
};
// -----------------------------------------------------------------------------
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;
}
@@ -106,10 +168,15 @@ int main(int argc, char* argv[]) {
std::string host = argv[1];
std::string port = argv[2];
int timeout_seconds = -1;
if (argc > 3) {
timeout_seconds = std::atoi(argv[3]);
}
boost::asio::io_context io_context;
BookListClient list_client(io_context, host, port);
BookDetailClient detail_client(io_context, host, port);
BookListClient list_client(io_context, host, port, timeout_seconds);
BookDetailClient detail_client(io_context, host, port, timeout_seconds);
// Response handler.
auto handler = [](webcc::HttpResponsePtr response, webcc::Error error,
@@ -126,16 +193,20 @@ int main(int argc, char* argv[]) {
};
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.CreateBook("1984", 12.3, [](std::string id) {
std::cout << "ID: " << id << std::endl;
});
list_client.ListBooks(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;
}
+6 -1
View File
@@ -1,6 +1,11 @@
set(TARGET_NAME rest_book_client)
set(SRCS main.cc)
set(SRCS
../common/book.cc
../common/book.h
../common/book_json.cc
../common/book_json.h
main.cc)
add_executable(${TARGET_NAME} ${SRCS})
+17 -10
View File
@@ -5,6 +5,9 @@
#include "webcc/logger.h"
#include "webcc/rest_client.h"
#include "example/common/book.h"
#include "example/common/book_json.h"
// In order to run with VLD, please copy the following files to the example
// output folder from "third_party\win32\bin":
// - dbghelp.dll
@@ -41,7 +44,7 @@ static Json::Value StringToJson(const std::string& str) {
// -----------------------------------------------------------------------------
class BookClientBase {
public:
public:
BookClientBase(const std::string& host, const std::string& port,
int timeout_seconds)
: rest_client_(host, port) {
@@ -50,7 +53,7 @@ public:
virtual ~BookClientBase() = default;
protected:
protected:
void PrintSeparateLine() {
std::cout << "--------------------------------";
std::cout << "--------------------------------";
@@ -121,17 +124,16 @@ public:
: BookClientBase(host, port, timeout_seconds) {
}
bool GetBook(const std::string& id) {
bool GetBook(const std::string& id, Book* book) {
PrintSeparateLine();
std::cout << "GetBook: " << id << std::endl;
if (!rest_client_.Get("/book/" + id)) {
if (!rest_client_.Get("/books/" + id)) {
PrintError();
return false;
}
std::cout << rest_client_.response_content() << std::endl;
return true;
return JsonStringToBook(rest_client_.response_content(), book);
}
bool UpdateBook(const std::string& id, const std::string& title,
@@ -145,7 +147,7 @@ public:
json["title"] = title;
json["price"] = price;
if (!rest_client_.Put("/book/" + id, JsonToString(json))) {
if (!rest_client_.Put("/books/" + id, JsonToString(json))) {
PrintError();
return false;
}
@@ -158,7 +160,7 @@ public:
PrintSeparateLine();
std::cout << "DeleteBook: " << id << std::endl;
if (!rest_client_.Delete("/book/" + id)) {
if (!rest_client_.Delete("/books/" + id)) {
PrintError();
return false;
}
@@ -201,9 +203,14 @@ int main(int argc, char* argv[]) {
std::string id;
list_client.CreateBook("1984", 12.3, &id);
detail_client.GetBook(id);
Book book;
if (detail_client.GetBook(id, &book)) {
std::cout << "Book " << id << ": " << book << std::endl;
}
detail_client.UpdateBook(id, "1Q84", 32.1);
detail_client.GetBook(id);
detail_client.GetBook(id, &book);
detail_client.DeleteBook(id);
list_client.ListBooks();
+2
View File
@@ -3,6 +3,8 @@ set(TARGET_NAME rest_book_server)
set(SRCS
../common/book.cc
../common/book.h
../common/book_json.cc
../common/book_json.h
services.cc
services.h
main.cc)
+1 -1
View File
@@ -52,7 +52,7 @@ int main(int argc, char* argv[]) {
"/books", false);
server.Bind(std::make_shared<BookDetailService>(sleep_seconds),
"/book/(\\d+)", true);
"/books/(\\d+)", true);
server.Run();
+10 -37
View File
@@ -8,36 +8,12 @@
#include "webcc/logger.h"
#include "example/common/book.h"
#include "example/common/book_json.h"
// -----------------------------------------------------------------------------
static BookStore g_book_store;
static Json::Value BookToJson(const Book& book) {
Json::Value root;
root["id"] = book.id;
root["title"] = book.title;
root["price"] = book.price;
return root;
}
static bool JsonToBook(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.
@@ -49,13 +25,12 @@ bool BookListService::Get(const webcc::UrlQuery& /*query*/,
std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds_));
}
Json::Value root(Json::arrayValue);
Json::Value json(Json::arrayValue);
for (const Book& book : g_book_store.books()) {
root.append(BookToJson(book));
json.append(BookToJson(book));
}
Json::StreamWriterBuilder builder;
*response_content = Json::writeString(builder, root);
*response_content = JsonToString(json);
return true;
}
@@ -69,14 +44,13 @@ bool BookListService::Post(const std::string& request_content,
}
Book book;
if (JsonToBook(request_content, &book)) {
if (JsonStringToBook(request_content, &book)) {
std::string id = g_book_store.AddBook(book);
Json::Value root;
root["id"] = id;
Json::Value json;
json["id"] = id;
Json::StreamWriterBuilder builder;
*response_content = Json::writeString(builder, root);
*response_content = JsonToString(json);
return true;
}
@@ -102,8 +76,7 @@ bool BookDetailService::Get(const std::vector<std::string>& url_sub_matches,
const Book& book = g_book_store.GetBook(book_id);
if (!book.IsNull()) {
Json::StreamWriterBuilder builder;
*response_content = Json::writeString(builder, BookToJson(book));
*response_content = BookToJsonString(book);
return true;
}
@@ -126,7 +99,7 @@ bool BookDetailService::Put(const std::vector<std::string>& url_sub_matches,
const std::string& book_id = url_sub_matches[0];
Book book;
if (JsonToBook(request_content, &book)) {
if (JsonStringToBook(request_content, &book)) {
book.id = book_id;
return g_book_store.UpdateBook(book);
}