1 #include "client_http.hpp"
2 #include "server_http.hpp"
3 #include <future>
4
5 // Added for the json-example
6 #define BOOST_SPIRIT_THREADSAFE
7 #include <boost/property_tree/json_parser.hpp>
8 #include <boost/property_tree/ptree.hpp>
9
10 // Added for the default_resource example
11 #include <algorithm>
12 #include <boost/filesystem.hpp>
13 #include <fstream>
14 #include <vector>
15 #ifdef HAVE_OPENSSL
16 #include "crypto.hpp"
17 #endif
18
19 using namespace std;
20 // Added for the json-example:
21 using namespace boost::property_tree;
22
23 using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
24 using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>;
25
main()26 int main() {
27 // HTTP-server at port 8080 using 1 thread
28 // Unless you do more heavy non-threaded processing in the resources,
29 // 1 thread is usually faster than several threads
30 HttpServer server;
31 server.config.port = 8080;
32
33 // Add resources using path-regex and method-string, and an anonymous function
34 // POST-example for the path /string, responds the posted string
35 server.resource["^/string$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
36 // Retrieve string:
37 auto content = request->content.string();
38 // request->content.string() is a convenience function for:
39 // stringstream ss;
40 // ss << request->content.rdbuf();
41 // auto content=ss.str();
42
43 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
44 << content;
45
46
47 // Alternatively, use one of the convenience functions, for instance:
48 // response->write(content);
49 };
50
51 // POST-example for the path /json, responds firstName+" "+lastName from the posted json
52 // Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
53 // Example posted json:
54 // {
55 // "firstName": "John",
56 // "lastName": "Smith",
57 // "age": 25
58 // }
59 server.resource["^/json$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
60 try {
61 ptree pt;
62 read_json(request->content, pt);
63
64 auto name = pt.get<string>("firstName") + " " + pt.get<string>("lastName");
65
66 *response << "HTTP/1.1 200 OK\r\n"
67 << "Content-Length: " << name.length() << "\r\n\r\n"
68 << name;
69 }
70 catch(const exception &e) {
71 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n"
72 << e.what();
73 }
74
75
76 // Alternatively, using a convenience function:
77 // try {
78 // ptree pt;
79 // read_json(request->content, pt);
80
81 // auto name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
82 // response->write(name);
83 // }
84 // catch(const exception &e) {
85 // response->write(SimpleWeb::StatusCode::client_error_bad_request, e.what());
86 // }
87 };
88
89 // GET-example for the path /info
90 // Responds with request-information
91 server.resource["^/info$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
92 stringstream stream;
93 stream << "<h1>Request from " << request->remote_endpoint().address().to_string() << ":" << request->remote_endpoint().port() << "</h1>";
94
95 stream << request->method << " " << request->path << " HTTP/" << request->http_version;
96
97 stream << "<h2>Query Fields</h2>";
98 auto query_fields = request->parse_query_string();
99 for(auto &field : query_fields)
100 stream << field.first << ": " << field.second << "<br>";
101
102 stream << "<h2>Header Fields</h2>";
103 for(auto &field : request->header)
104 stream << field.first << ": " << field.second << "<br>";
105
106 response->write(stream);
107 };
108
109 // GET-example for the path /match/[number], responds with the matched string in path (number)
110 // For instance a request GET /match/123 will receive: 123
111 server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
112 response->write(request->path_match[1].str());
113 };
114
115 // GET-example simulating heavy work in a separate thread
116 server.resource["^/work$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
117 thread work_thread([response] {
118 this_thread::sleep_for(chrono::seconds(5));
119 response->write("Work done");
120 });
121 work_thread.detach();
122 };
123
124 // Default GET-example. If no other matches, this anonymous function will be called.
125 // Will respond with content in the web/-directory, and its subdirectories.
126 // Default file: index.html
127 // Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
128 server.default_resource["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
129 try {
130 auto web_root_path = boost::filesystem::canonical("web");
131 auto path = boost::filesystem::canonical(web_root_path / request->path);
132 // Check if path is within web_root_path
133 if(distance(web_root_path.begin(), web_root_path.end()) > distance(path.begin(), path.end()) ||
134 !equal(web_root_path.begin(), web_root_path.end(), path.begin()))
135 throw invalid_argument("path must be within root path");
136 if(boost::filesystem::is_directory(path))
137 path /= "index.html";
138
139 SimpleWeb::CaseInsensitiveMultimap header;
140
141 // Uncomment the following line to enable Cache-Control
142 // header.emplace("Cache-Control", "max-age=86400");
143
144 #ifdef HAVE_OPENSSL
145 // Uncomment the following lines to enable ETag
146 // {
147 // ifstream ifs(path.string(), ifstream::in | ios::binary);
148 // if(ifs) {
149 // auto hash = SimpleWeb::Crypto::to_hex_string(SimpleWeb::Crypto::md5(ifs));
150 // header.emplace("ETag", "\"" + hash + "\"");
151 // auto it = request->header.find("If-None-Match");
152 // if(it != request->header.end()) {
153 // if(!it->second.empty() && it->second.compare(1, hash.size(), hash) == 0) {
154 // response->write(SimpleWeb::StatusCode::redirection_not_modified, header);
155 // return;
156 // }
157 // }
158 // }
159 // else
160 // throw invalid_argument("could not read file");
161 // }
162 #endif
163
164 auto ifs = make_shared<ifstream>();
165 ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
166
167 if(*ifs) {
168 auto length = ifs->tellg();
169 ifs->seekg(0, ios::beg);
170
171 header.emplace("Content-Length", to_string(length));
172 response->write(header);
173
174 // Trick to define a recursive function within this scope (for example purposes)
175 class FileServer {
176 public:
177 static void read_and_send(const shared_ptr<HttpServer::Response> &response, const shared_ptr<ifstream> &ifs) {
178 // Read and send 128 KB at a time
179 static vector<char> buffer(131072); // Safe when server is running on one thread
180 streamsize read_length;
181 if((read_length = ifs->read(&buffer[0], static_cast<streamsize>(buffer.size())).gcount()) > 0) {
182 response->write(&buffer[0], read_length);
183 if(read_length == static_cast<streamsize>(buffer.size())) {
184 response->send([response, ifs](const SimpleWeb::error_code &ec) {
185 if(!ec)
186 read_and_send(response, ifs);
187 else
188 cerr << "Connection interrupted" << endl;
189 });
190 }
191 }
192 }
193 };
194 FileServer::read_and_send(response, ifs);
195 }
196 else
197 throw invalid_argument("could not read file");
198 }
199 catch(const exception &e) {
200 response->write(SimpleWeb::StatusCode::client_error_bad_request, "Could not open path " + request->path + ": " + e.what());
201 }
202 };
203
204 server.on_error = [](shared_ptr<HttpServer::Request> /*request*/, const SimpleWeb::error_code & /*ec*/) {
205 // Handle errors here
206 // Note that connection timeouts will also call this handle with ec set to SimpleWeb::errc::operation_canceled
207 };
208
209 // Start server and receive assigned port when server is listening for requests
210 promise<unsigned short> server_port;
211 thread server_thread([&server, &server_port]() {
212 // Start server
213 server.start([&server_port](unsigned short port) {
214 server_port.set_value(port);
215 });
216 });
217 cout << "Server listening on port " << server_port.get_future().get() << endl
218 << endl;
219
220 // Client examples
221 string json_string = "{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
222
223 // Synchronous request examples
224 {
225 HttpClient client("localhost:8080");
226 try {
227 cout << "Example GET request to http://localhost:8080/match/123" << endl;
228 auto r1 = client.request("GET", "/match/123");
229 cout << "Response content: " << r1->content.rdbuf() << endl // Alternatively, use the convenience function r1->content.string()
230 << endl;
231
232 cout << "Example POST request to http://localhost:8080/string" << endl;
233 auto r2 = client.request("POST", "/string", json_string);
234 cout << "Response content: " << r2->content.rdbuf() << endl
235 << endl;
236 }
237 catch(const SimpleWeb::system_error &e) {
238 cerr << "Client request error: " << e.what() << endl;
239 }
240 }
241
242 // Asynchronous request example
243 {
244 HttpClient client("localhost:8080");
245 cout << "Example POST request to http://localhost:8080/json" << endl;
246 client.request("POST", "/json", json_string, [](shared_ptr<HttpClient::Response> response, const SimpleWeb::error_code &ec) {
247 if(!ec)
248 cout << "Response content: " << response->content.rdbuf() << endl;
249 });
250 client.io_service->run();
251 }
252
253 server_thread.join();
254 }
255