Rework the body of request and response

This commit is contained in:
Chunting Gu
2019-07-03 17:37:44 +08:00
parent b9f2ba6a41
commit 98aeeae012
39 changed files with 1122 additions and 677 deletions
+40 -32
View File
@@ -44,8 +44,8 @@ int main() {
// Send a HTTP GET request.
auto r = session.Get("http://httpbin.org/get");
// Print the response content data.
std::cout << r->content() << std::endl;
// Print the response data.
std::cout << r->data() << std::endl;
} catch (const webcc::Error& error) {
std::cout << error << std::endl;
@@ -57,8 +57,8 @@ int main() {
The `Get()` method is nothing but a shortcut of `Request()`. Using `Request()` directly is more complicated:
```cpp
auto r = session.Request(webcc::RequestBuilder{}.Get().
Url("http://httpbin.org/get")
auto r = session.Request(webcc::RequestBuilder{}.
Get("http://httpbin.org/get")
());
```
As you can see, a helper class named `RequestBuilder` is used to chain the parameters and finally build (don't miss the `()` operator) a request object.
@@ -69,8 +69,8 @@ Both the shortcut and `Request()` accept URL query parameters:
// Query parameters are passed using a std::vector.
session.Get("http://httpbin.org/get", { "key1", "value1", "key2", "value2" });
session.Request(webcc::RequestBuilder{}.Get().
Url("http://httpbin.org/get").
session.Request(webcc::RequestBuilder{}.
Get("http://httpbin.org/get").
Query("key1", "value1").
Query("key2", "value2")
());
@@ -82,8 +82,8 @@ session.Get("http://httpbin.org/get",
{"key1", "value1", "key2", "value2"},
{"Accept", "application/json"}); // Also a std::vector
session.Request(webcc::RequestBuilder{}.Get().
Url("http://httpbin.org/get").
session.Request(webcc::RequestBuilder{}.
Get("http://httpbin.org/get").
Query("key1", "value1").
Query("key2", "value2").
Header("Accept", "application/json")
@@ -100,7 +100,7 @@ Listing GitHub public events is not a big deal:
```cpp
auto r = session.Get("https://api.github.com/events");
```
You can then parse `r->content()` to JSON object with your favorite JSON library. My choice for the examples is [jsoncpp](https://github.com/open-source-parsers/jsoncpp). But the library itself doesn't understand JSON nor require one. It's up to you to choose the most appropriate JSON library.
You can then parse `r->data()` to JSON object with your favorite JSON library. My choice for the examples is [jsoncpp](https://github.com/open-source-parsers/jsoncpp). But the library itself doesn't understand JSON nor require one. It's up to you to choose the most appropriate JSON library.
## Server API Examples
@@ -119,7 +119,7 @@ class BookListView : public webcc::View {
public:
webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
if (request->method() == "GET") {
return Get(request->query());
return Get(request);
}
if (request->method() == "POST") {
@@ -131,10 +131,10 @@ public:
private:
// Get a list of books based on query parameters.
webcc::ResponsePtr Get(const webcc::UrlQuery& query);
webcc::ResponsePtr Get(webcc::RequestPtr request);
// Create a new book.
// The new book's data is attached as request content in JSON format.
// The new book's data is attached as request data in JSON format.
webcc::ResponsePtr Post(webcc::RequestPtr request);
};
```
@@ -148,15 +148,15 @@ class BookDetailView : public webcc::View {
public:
webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
if (request->method() == "GET") {
return Get(request->args(), request->query());
return Get(request);
}
if (request->method() == "PUT") {
return Put(request, request->args());
return Put(request);
}
if (request->method() == "DELETE") {
return Delete(request->args());
return Delete(request);
}
return {};
@@ -164,30 +164,27 @@ public:
protected:
// Get the detailed information of a book.
webcc::ResponsePtr Get(const webcc::UrlArgs& args,
const webcc::UrlQuery& query);
webcc::ResponsePtr Get(webcc::RequestPtr request);
// Update a book.
webcc::ResponsePtr Put(webcc::RequestPtr request,
const webcc::UrlArgs& args);
webcc::ResponsePtr Put(webcc::RequestPtr request);
// Delete a book.
webcc::ResponsePtr Delete(const webcc::UrlArgs& args);
webcc::ResponsePtr Delete(webcc::RequestPtr request);
};
```
The detailed implementation is out of the scope of this README, but here is an example:
```cpp
webcc::ResponsePtr BookDetailView::Get(const webcc::UrlArgs& args,
const webcc::UrlQuery& query) {
if (args.size() != 1) {
webcc::ResponsePtr BookDetailView::Get(webcc::RequestPtr request) {
if (request->args().size() != 1) {
// Using kNotFound means the resource specified by the URL cannot be found.
// kBadRequest could be another choice.
return webcc::ResponseBuilder{}.NotFound()();
}
const std::string& book_id = args[0];
const std::string& book_id = request->args()[0];
// Get the book by ID from, e.g., the database.
// ...
@@ -195,24 +192,35 @@ webcc::ResponsePtr BookDetailView::Get(const webcc::UrlArgs& args,
if (<NotFound>) {
// There's no such book with the given ID.
return webcc::ResponseBuilder{}.NotFound()();
} else {
// Convert the book to JSON string and set as response content.
return webcc::ResponseBuilder{}.OK().Data(<JsonStringOfTheBook>).Json()();
}
// Convert the book to JSON string and set as response data.
return webcc::ResponseBuilder{}.OK().Data(<JsonStringOfTheBook>).Json().Utf8();
}
```
Last step, route URLs to the proper views and run the server:
```cpp
webcc::Server server(8080, 2);
int main(int argc, char* argv[]) {
// ...
server.Route("/books", std::make_shared<BookListView>(), { "GET", "POST" });
try {
webcc::Server server(8080, 2);
server.Route(webcc::R("/books/(\\d+)"), std::make_shared<BookDetailView>(),
{ "GET", "PUT", "DELETE" });
server.Route("/books", std::make_shared<BookListView>(), { "GET", "POST" });
server.Run();
server.Route(webcc::R("/books/(\\d+)"), std::make_shared<BookDetailView>(),
{ "GET", "PUT", "DELETE" });
server.Run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
```
Please see [examples/rest_book_server.cc](https://github.com/sprinfall/webcc/tree/master/examples/rest_book_server.cc) for more details.