Repository navigation
Expand file tree
/
Copy pathserver.cpp
More file actions
79 lines (68 loc) · 2.63 KB
/
Copy pathserver.cpp
File metadata and controls
79 lines (68 loc) · 2.63 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
#include "../polyweb.hpp"
#include <iostream>
#include <stdlib.h>
int main() {
(void) pn::init();
pw::Server server;
server.route("/hello_world",
pw::Route {
[](const pw::Connection& conn, const pw::Request& req) {
return pw::Response(200, "Hello, World!", {{"Content-Type", "text/plain"}});
},
});
// Since this is a wildcard route, anything may come after /wildcard/
server.route("/wildcard/",
pw::Route {
[](const pw::Connection& conn, const pw::Request& req) {
return pw::Response(200, req.target, {{"Content-Type", "text/plain"}});
},
true,
});
server.route("/multiply",
pw::Route {
[](const pw::Connection& conn, const pw::Request& req) {
int x = std::stoi(req.query_parameters->find("x")->second);
int y = std::stoi(req.query_parameters->find("y")->second);
return pw::Response(200, std::to_string(x * y), {{"Content-Type", "text/plain"}});
},
});
server.route("/send_stream",
pw::Route {
[](const pw::Connection& conn, const pw::Request& req) {
return pw::Response(200, []() -> std::generator<std::vector<char>> {
for (int i = 0; i < 10; ++i) {
std::string str = std::to_string(i);
co_yield std::vector<char>(str.begin(), str.end());
}
},
{{"Content-Type", "text/plain"}});
},
});
server.route("/recv_stream",
pw::Route {
[](pw::Connection& conn, pw::RequestReceiver& req) {
std::vector<char> body;
req.recv_cb = [&body](std::vector<char> chunk) {
body.insert(body.end(), chunk.begin(), chunk.end());
return true;
};
if (pn::Status result = conn.recv(req, PW_HTTP_MESSAGE_PART_BODY); !result) {
return pw::Response(500, result.error().message());
}
return pw::Response(200, body);
},
false,
false, // tells Polyweb not to parse the body itself
});
if (pn::Status result = server.bind("0.0.0.0", 8000); !result) {
std::cerr << "Error: " << result.error().message() << std::endl;
return 1;
}
if (pn::Status result = server.listen(); !result) {
std::cerr << "Error: " << result.error().message() << std::endl;
return 1;
}
(void) server.close();
(void) pn::quit();
return 0;
}