-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleserver.cpp
123 lines (94 loc) · 2.74 KB
/
simpleserver.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
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
119
120
121
122
123
/*
* simpleserver.cpp
*
* Created on: Jun 26, 2015
* Author: Marco Massenzio, http://codetrips.com
*
* This code is explained in a blog entry at the above URL.
*/
#include <chrono>
#include <iostream>
#include <thread>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/process.hpp>
#include <stout/json.hpp>
#include <stout/numify.hpp>
using std::cerr;
using std::cout;
using std::endl;
using std::chrono::seconds;
using process::Future;
using process::Promise;
using process::http::Request;
using process::http::OK;
using process::http::InternalServerError;
class SimpleProcess : public process::Process<SimpleProcess> {
public:
SimpleProcess() : ProcessBase("simple") {}
virtual void initialize();
Future<bool> done() {
cout << "are we done yet? " << endl;
return shouldQuit.future();
}
void shutdown() {
cout << "Shutting down server..." << endl;
this->shouldQuit.set(true);
}
private:
Promise<bool> shouldQuit;
};
void SimpleProcess::initialize() {
route(
"/add",
"Adds the two query arguments",
[] (Request request) {
int a = numify<int>(request.query["a"]).get();
int b = numify<int>(request.query["b"]).get();
std::ostringstream result;
result << "{ \"result\": " << a + b << "}";
JSON::Value body = JSON::parse(result.str()).get();
return OK(body);
});
route(
"/quit",
"Shuts the server down",
[this] (Request request) {
this->shutdown();
return OK("Shutting down server");
});
route(
"/error",
"Forces an Internal Server Error (500)",
[this](Request request) {
this->shouldQuit.set(false);
return InternalServerError("We encountered an error");
});
}
int runServer() {
int retCode;
SimpleProcess simpleProcess;
process::PID<SimpleProcess> pid = process::spawn(simpleProcess);
cout << "Running Server on http://" << process::address().ip << ":"
<< process::address().port << "/simple" << endl
<< "Use /quit to terminate server..." << endl;
cout << "Waiting for it to terminate..." << endl;
Future<bool> quit = simpleProcess.done();
quit.await();
// wait for the server to complete the request
std::this_thread::sleep_for(seconds(2));
if (!quit.get()) {
cerr << "The server encountered an error and is exiting now" << endl;
retCode = EXIT_FAILURE;
} else {
cout << "Done" << endl;
retCode = EXIT_SUCCESS;
}
process::terminate(simpleProcess);
process::wait(simpleProcess);
return retCode;
}
int main(int argc, char *argv[]){
return runServer();
}