1 #include "server_http.hpp"
2 #include "client_http.hpp"
3
4 #include <cassert>
5
6 using namespace std;
7
8 typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
9 typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
10
main()11 int main() {
12 HttpServer server;
13 server.config.port=8080;
14
15 server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
16 auto content=request->content.string();
17
18 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
19 };
20
21 server.resource["^/info$"]["GET"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
22 stringstream content_stream;
23 content_stream << request->method << " " << request->path << " " << request->http_version << " ";
24 content_stream << request->header.find("test parameter")->second;
25
26 content_stream.seekp(0, ios::end);
27
28 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
29 };
30
31 server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
32 string number=request->path_match[1];
33 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
34 };
35
36 thread server_thread([&server](){
37 //Start server
38 server.start();
39 });
40
41 this_thread::sleep_for(chrono::seconds(1));
42 {
43 HttpClient client("localhost:8080");
44
45 {
46 stringstream output;
47 auto r=client.request("POST", "/string", "A string");
48 output << r->content.rdbuf();
49 assert(output.str()=="A string");
50 }
51
52 {
53 stringstream output;
54 stringstream content("A string");
55 auto r=client.request("POST", "/string", content);
56 output << r->content.rdbuf();
57 assert(output.str()=="A string");
58 }
59
60 {
61 stringstream output;
62 auto r=client.request("GET", "/info", "", {{"Test Parameter", "test value"}});
63 output << r->content.rdbuf();
64 assert(output.str()=="GET /info 1.1 test value");
65 }
66
67 {
68 stringstream output;
69 auto r=client.request("GET", "/match/123");
70 output << r->content.rdbuf();
71 assert(output.str()=="123");
72 }
73 }
74 {
75 HttpClient client("localhost:8080");
76
77 // test performing the stream version of the request methods first
78 {
79 stringstream output;
80 stringstream content("A string");
81 auto r=client.request("POST", "/string", content);
82 output << r->content.rdbuf();
83 assert(output.str()=="A string");
84 }
85
86 {
87 stringstream output;
88 auto r=client.request("POST", "/string", "A string");
89 output << r->content.rdbuf();
90 assert(output.str()=="A string");
91 }
92 }
93
94 server.stop();
95 server_thread.join();
96
97 return 0;
98 }
99