Allow to stop server and restart server; allow to run loop in multiple threads.

This commit is contained in:
Chunting Gu
2019-07-30 10:35:51 +08:00
parent 0f0f6fdf8e
commit 673a98cffb
16 changed files with 465 additions and 287 deletions
+3
View File
@@ -61,3 +61,6 @@ target_link_libraries(file_upload_server ${EXAMPLE_LIBS})
add_executable(static_server static_server.cc)
target_link_libraries(static_server ${EXAMPLE_LIBS})
add_executable(server_states server_states.cc)
target_link_libraries(server_states ${EXAMPLE_LIBS})
+1 -1
View File
@@ -53,7 +53,7 @@ int main(int argc, char* argv[]) {
server.Route("/upload", std::make_shared<FileUploadView>(), { "POST" });
server.Start();
server.Run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
+1 -1
View File
@@ -21,7 +21,7 @@ int main() {
server.Route("/", std::make_shared<HelloView>());
server.Start();
server.Run();
} catch (const std::exception&) {
return 1;
+146 -155
View File
@@ -19,155 +19,157 @@
// -----------------------------------------------------------------------------
class BookClientBase {
class BookClient {
public:
BookClientBase(webcc::ClientSession& session, const std::string& url)
: session_(session), url_(url) {
}
explicit BookClient(const std::string& url, int timeout = 0);
virtual ~BookClientBase() = default;
~BookClient() = default;
protected:
// Check HTTP response status.
bool CheckStatus(webcc::ResponsePtr response, int expected_status) {
int status = response->status();
if (status != expected_status) {
LOG_ERRO("HTTP status error (actual: %d, expected: %d).",
status, expected_status);
return false;
}
return true;
}
bool ListBooks(std::list<Book>* books);
protected:
std::string url_;
bool CreateBook(const std::string& title, double price, std::string* id);
webcc::ClientSession& session_;
};
// -----------------------------------------------------------------------------
class BookListClient : public BookClientBase {
public:
BookListClient(webcc::ClientSession& session, const std::string& url)
: BookClientBase(session, url) {
}
bool ListBooks(std::list<Book>* books) {
try {
auto r = session_.Get(url_ + "/books");
if (!CheckStatus(r, webcc::Status::kOK)) {
// Response HTTP status error.
return false;
}
Json::Value rsp_json = StringToJson(r->data());
if (!rsp_json.isArray()) {
return false; // Should be a JSON array of books.
}
for (Json::ArrayIndex i = 0; i < rsp_json.size(); ++i) {
books->push_back(JsonToBook(rsp_json[i]));
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool CreateBook(const std::string& title, double price, std::string* id) {
Json::Value req_json;
req_json["title"] = title;
req_json["price"] = price;
try {
auto r = session_.Post(url_ + "/books", JsonToString(req_json), true);
if (!CheckStatus(r, webcc::Status::kCreated)) {
return false;
}
Json::Value rsp_json = StringToJson(r->data());
*id = rsp_json["id"].asString();
return !id->empty();
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
};
// -----------------------------------------------------------------------------
class BookDetailClient : public BookClientBase {
public:
BookDetailClient(webcc::ClientSession& session, const std::string& url)
: BookClientBase(session, url) {
}
bool GetBook(const std::string& id, Book* book) {
try {
auto r = session_.Get(url_ + "/books/" + id);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return JsonStringToBook(r->data(), book);
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool GetBook(const std::string& id, Book* book);
bool UpdateBook(const std::string& id, const std::string& title,
double price) {
Json::Value json;
json["title"] = title;
json["price"] = price;
double price);
try {
auto r = session_.Put(url_ + "/books/" + id, JsonToString(json), true);
bool DeleteBook(const std::string& id);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
private:
// Check HTTP response status.
bool CheckStatus(webcc::ResponsePtr response, int expected_status);
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool DeleteBook(const std::string& id) {
try {
auto r = session_.Delete(url_ + "/books/" + id);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
private:
std::string url_;
webcc::ClientSession session_;
};
// -----------------------------------------------------------------------------
BookClient::BookClient(const std::string& url, int timeout)
: url_(url), session_(timeout) {
// If the request has body, default to this content type.
// Optional.
session_.set_media_type("application/json");
session_.set_charset("utf-8");
}
bool BookClient::ListBooks(std::list<Book>* books) {
try {
auto r = session_.Get(url_ + "/books");
if (!CheckStatus(r, webcc::Status::kOK)) {
// Response HTTP status error.
return false;
}
Json::Value rsp_json = StringToJson(r->data());
if (!rsp_json.isArray()) {
return false; // Should be a JSON array of books.
}
for (Json::ArrayIndex i = 0; i < rsp_json.size(); ++i) {
books->push_back(JsonToBook(rsp_json[i]));
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::CreateBook(const std::string& title, double price,
std::string* id) {
Json::Value req_json;
req_json["title"] = title;
req_json["price"] = price;
try {
auto r = session_.Post(url_ + "/books", JsonToString(req_json), true);
if (!CheckStatus(r, webcc::Status::kCreated)) {
return false;
}
Json::Value rsp_json = StringToJson(r->data());
*id = rsp_json["id"].asString();
return !id->empty();
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::GetBook(const std::string& id, Book* book) {
try {
auto r = session_.Get(url_ + "/books/" + id);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return JsonStringToBook(r->data(), book);
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::UpdateBook(const std::string& id, const std::string& title,
double price) {
Json::Value json;
json["title"] = title;
json["price"] = price;
try {
auto r = session_.Put(url_ + "/books/" + id, JsonToString(json), true);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::DeleteBook(const std::string& id) {
try {
auto r = session_.Delete(url_ + "/books/" + id);
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::CheckStatus(webcc::ResponsePtr response, int expected_status) {
if (response->status() != expected_status) {
LOG_ERRO("HTTP status error (actual: %d, expected: %d).",
response->status(), expected_status);
return false;
}
return true;
}
// -----------------------------------------------------------------------------
void PrintSeparator() {
static const std::string s_line(80, '-');
std::cout << s_line << std::endl;
@@ -208,30 +210,19 @@ int main(int argc, char* argv[]) {
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE_FILE_OVERWRITE);
// Share the same session.
webcc::ClientSession session;
session.set_timeout(timeout);
// If the request has body, default to this content type.
// Optional.
session.set_media_type("application/json");
session.set_charset("utf-8");
BookListClient list_client(session, url);
BookDetailClient detail_client(session, url);
BookClient client(url, timeout);
PrintSeparator();
std::list<Book> books;
if (list_client.ListBooks(&books)) {
if (client.ListBooks(&books)) {
PrintBookList(books);
}
PrintSeparator();
std::string id;
if (list_client.CreateBook("1984", 12.3, &id)) {
if (client.CreateBook("1984", 12.3, &id)) {
std::cout << "Book ID: " << id << std::endl;
} else {
id = "1";
@@ -241,35 +232,35 @@ int main(int argc, char* argv[]) {
PrintSeparator();
books.clear();
if (list_client.ListBooks(&books)) {
if (client.ListBooks(&books)) {
PrintBookList(books);
}
PrintSeparator();
Book book;
if (detail_client.GetBook(id, &book)) {
if (client.GetBook(id, &book)) {
PrintBook(book);
}
PrintSeparator();
detail_client.UpdateBook(id, "1Q84", 32.1);
client.UpdateBook(id, "1Q84", 32.1);
PrintSeparator();
if (detail_client.GetBook(id, &book)) {
if (client.GetBook(id, &book)) {
PrintBook(book);
}
PrintSeparator();
detail_client.DeleteBook(id);
client.DeleteBook(id);
PrintSeparator();
books.clear();
if (list_client.ListBooks(&books)) {
if (client.ListBooks(&books)) {
PrintBookList(books);
}
+1 -3
View File
@@ -224,8 +224,6 @@ int main(int argc, char* argv[]) {
sleep_seconds = std::atoi(argv[2]);
}
std::size_t workers = 2;
try {
webcc::Server server(port);
@@ -237,7 +235,7 @@ int main(int argc, char* argv[]) {
std::make_shared<BookDetailView>(sleep_seconds),
{ "GET", "PUT", "DELETE" });
server.Start(workers);
server.Run(2);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
+50
View File
@@ -0,0 +1,50 @@
#include "webcc/logger.h"
#include "webcc/response_builder.h"
#include "webcc/server.h"
class HelloView : public webcc::View {
public:
webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
if (request->method() == "GET") {
return webcc::ResponseBuilder{}.OK().Body("Hello, World!")();
}
return {};
}
};
int main() {
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE);
try {
webcc::Server server(8080);
server.Route("/", std::make_shared<HelloView>());
// Run the server in a separate thread.
std::thread t([&server]() { server.Run(); });
// Let the server run for several seconds.
std::this_thread::sleep_for(std::chrono::seconds(3));
// Stop the server.
server.Stop();
// Wait for the server to finish.
t.join();
// Run the server again.
std::thread t2([&server]() { server.Run(); });
// Wait for the server to finish.
t2.join();
} catch (const std::exception&) {
// NOTE:
// Catch std::exception instead of webcc::Error.
// webcc::Error is for client only.
return 1;
}
return 0;
}
+1 -1
View File
@@ -28,7 +28,7 @@ int main(int argc, char* argv[]) {
try {
webcc::Server server(port, doc_root);
server.Start();
server.Run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;