-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
94 lines (75 loc) · 2.7 KB
/
Main.cpp
File metadata and controls
94 lines (75 loc) · 2.7 KB
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
/**
* Main.cpp
*/
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <cpprest/http_client.h>
#include "Server.hpp"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
void makeRequest() {
// Create http_client to send the request.
http_client client(U("http://localhost:3000"));
// Build request URI and start the request.
uri_builder builder(U("/api/v1/test"));
// Open stream to output file.
pplx::task<void> requestTask = client.request(methods::GET, builder.to_string())
// Handle response headers arriving.
.then([=] (http_response response) {
printf("Received response status code:%u\n", response.status_code());
// Extract json.
return response.extract_json();
})
// Print json.
.then([=] (pplx::task<json::value> previousTask) {
const json::value& value = previousTask.get();
std::cout << "Value: " << value.serialize() << "\n";
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try {
requestTask.wait();
} catch (const std::exception& e) {
printf("Error exception:%s\n", e.what());
}
}
std::condition_variable condition;
int main(int argc, char* argv[]) {
signal(SIGINT, [] (int signal) {
if (signal == SIGINT) {
std::cout << "\nSIGINT trapped...\n";
condition.notify_one();
}
});
string_t host = U("localhost");
string_t port = U("3000");
try {
// Create server
Server server(host, port);
server.get("/api/v1/test", [] (http_request req) {
std::cout <<"Route called???\n";
auto res = json::value::object();
res["foo"] = json::value::string("bar");
req.reply(status_codes::OK, res);
});
// Start server.
server.open().wait();
std::cout << "Listening at: " << server.endpoint() << "\n";
// Test calling the server.
makeRequest();
// Keep server running until user kills it.
std::mutex mutex;
std::unique_lock<std::mutex> lock { mutex };
condition.wait(lock);
lock.unlock();
std::cout << "Closing server...\n";
server.close().wait();
} catch (std::exception& ex) {
std::cerr << "Error: " << ex.what() << "\n";
return -1;
}
return 0;
}