-
Notifications
You must be signed in to change notification settings - Fork 13
/
example.cpp
62 lines (56 loc) · 2.35 KB
/
example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "httpcpp.h"
#include <iostream>
using namespace std;
// client: curl "http://127.0.0.1:8850/a/10"
class HttpRequestHandlerA : public HttpRequestHandler {
public:
void get(HttpRequest* const request, const vector<string>& args) {
cout << "-----------------------------------" << endl;
cout << "Handler A receives:" << endl;
cout << "method: " << request->get_method() << endl;
cout << "path : " << request->get_path() << endl;
cout << "body : " << request->get_body() << endl;
for (int i = 0; i < args.size(); i++) {
cout << "arg : " << args[i] << endl;
}
this->reply(request, 200, "A=>" + request->get_body());
}
};
// client: curl "http://127.0.0.1:8850/b/10/" -d "abcxyz"
class HttpRequestHandlerB : public HttpRequestHandler {
public:
void post(HttpRequest* const request, const vector<string>& args) {
cout << "-----------------------------------" << endl;
cout << "Handler B receives:" << endl;
cout << "method: " << request->get_method() << endl;
cout << "path : " << request->get_path() << endl;
cout << "body : " << request->get_body() << endl;
for (int i = 0; i < args.size(); i++) {
cout << "arg : " << args[i] << endl;
}
this->reply(request, 200, "B=>" + request->get_body());
}
};
class HttpResponseHandlerC : public HttpResponseHandler {
public:
void handle(HttpResponse* const response) {
cout << "-----------------------------------" << endl;
cout << "Handler C receives:" << endl;
cout << "code : " << response->get_code() << endl;
cout << "body : " << response->get_body() << endl;
}
};
int main() {
// server
AsyncHttpServer* server = new AsyncHttpServer(8850);
server->add_handler("^/a/([[:digit:]]+)$", new HttpRequestHandlerA());
server->add_handler("^/b/([[:digit:]]+)$", new HttpRequestHandlerB());
// client
AsyncHttpClient* client = new AsyncHttpClient();
client->fetch("127.0.0.1", 8850, "GET", "/a/10", "aaa",
new HttpResponseHandlerC());
client->fetch("127.0.0.1", 8850, "POST", "/b/10", "bbb",
new HttpResponseHandlerC());
// start
IOLoop::instance()->start();
}