-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMyFirstServer.cc
118 lines (89 loc) · 2.77 KB
/
MyFirstServer.cc
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <gflags/gflags.h>
#include <folly/Memory.h>
#include <folly/Portability.h>
#include <folly/io/async/EventBaseManager.h>
#include <proxygen/httpserver/HTTPServer.h>
#include <proxygen/httpserver/RequestHandlerFactory.h>
#include <proxygen/httpserver/ResponseHandler.h>
#include <proxygen/httpserver/ResponseBuilder.h>
#include <unistd.h>
#include <iostream>
using namespace proxygen;
using folly::EventBase;
using folly::EventBaseManager;
using folly::SocketAddress;
using namespace std;
using Protocol = HTTPServer::Protocol;
DEFINE_int32(http_port, 11000, "Port to listen on with HTTP protocol");
class MyHandler : public RequestHandler {
public:
MyHandler() : m_body(new folly::IOBuf(folly::IOBuf::CopyBufferOp::COPY_BUFFER, s_defaultBody.data(), s_defaultBody.size())) {
cout << __PRETTY_FUNCTION__ << endl;
}
void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers)
noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
}
void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
}
void onEOM() noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
ResponseBuilder(downstream_)
.status(200, "OK")
.header("Content-type", "text/plain")
.body(move(m_body))
.sendWithEOM();
}
void onUpgrade(proxygen::UpgradeProtocol proto) noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
}
void requestComplete() noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
delete this;
}
void onError(proxygen::ProxygenError err) noexcept override
{
cout << __PRETTY_FUNCTION__ << endl;
}
protected:
unique_ptr<folly::IOBuf> m_body;
static string s_defaultBody;
};
string MyHandler::s_defaultBody("It works!\n");
class MyHandlerFactory : public RequestHandlerFactory {
public:
void onServerStart(folly::EventBase* evb) noexcept override {
}
void onServerStop() noexcept override {
}
RequestHandler* onRequest(RequestHandler*, HTTPMessage*) noexcept override {
return new MyHandler();
}
private:
};
int main(int argc, char *argv[])
{
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
std::vector<HTTPServer::IPConfig> IPs = {
{SocketAddress("localhost", FLAGS_http_port, true), Protocol::HTTP}
};
HTTPServerOptions options;
options.handlerFactories = RequestHandlerChain()
.addThen<MyHandlerFactory>()
.build();
HTTPServer server(std::move(options));
server.bind(IPs);
std::thread t([&] () {
server.start();
});
t.join();
return 0;
}