1 #include "server_http.hpp"
2 #include "client_http.hpp"
4 //Added for the json-example
5 #define BOOST_SPIRIT_THREADSAFE
6 #include <boost/property_tree/ptree.hpp>
7 #include <boost/property_tree/json_parser.hpp>
9 //Added for the default_resource example
11 #include <boost/filesystem.hpp>
19 //Added for the json-example:
20 using namespace boost::property_tree;
22 typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
23 typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
25 //Added for the default_resource example
26 void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
27 const shared_ptr<ifstream> &ifs);
30 //HTTP-server at port 8080 using 1 thread
31 //Unless you do more heavy non-threaded processing in the resources,
32 //1 thread is usually faster than several threads
34 server.config.port=80;
36 //Add resources using path-regex and method-string, and an anonymous function
37 //POST-example for the path /string, responds the posted string
38 server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
40 auto content=request->content.string();
41 //request->content.string() is a convenience function for:
43 //ss << request->content.rdbuf();
44 //string content=ss.str();
46 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
49 //POST-example for the path /json, responds firstName+" "+lastName from the posted json
50 //Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
51 //Example posted json:
53 // "firstName": "John",
54 // "lastName": "Smith",
57 server.resource["^/json$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
60 read_json(request->content, pt);
62 string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
64 *response << "HTTP/1.1 200 OK\r\n"
65 << "Content-Type: application/json\r\n"
66 << "Content-Length: " << name.length() << "\r\n\r\n"
70 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
74 //GET-example for the path /info
75 //Responds with request-information
76 server.resource["^/info$"]["GET"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
77 stringstream content_stream;
78 content_stream << "<h1>Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")</h1>";
79 content_stream << request->method << " " << request->path << " HTTP/" << request->http_version << "<br>";
80 for(auto& header: request->header) {
81 content_stream << header.first << ": " << header.second << "<br>";
84 //find length of content_stream (length received using content_stream.tellp())
85 content_stream.seekp(0, ios::end);
87 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
90 //GET-example for the path /match/[number], responds with the matched string in path (number)
91 //For instance a request GET /match/123 will receive: 123
92 server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
93 string number=request->path_match[1];
94 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
97 //Get example simulating heavy work in a separate thread
98 server.resource["^/work$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
99 thread work_thread([response] {
100 this_thread::sleep_for(chrono::seconds(5));
101 string message="Work done";
102 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << message.length() << "\r\n\r\n" << message;
104 work_thread.detach();
107 server.resource["^/getAvailableNetwork$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
108 thread work_thread([response] {
109 this_thread::sleep_for(chrono::seconds(5));
110 // string message="Work done";
111 string json_string="{\"result\":[{\"ch\":13,\"ha\":\"18B43000003D2785\",\"nn\":\"NEST-PAN-C1E7\",\"pi\":\"0xC19B\",\"xp\":\"EEA74CE1EDFA2E8A\"}]}";
112 // string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
113 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << json_string.length() << "\r\nContent-Type:application/json; charset=utf-8" << "\r\n\r\n" << json_string;
115 work_thread.detach();
118 //Default GET-example. If no other matches, this anonymous function will be called.
119 //Will respond with content in the web/-directory, and its subdirectories.
120 //Default file: index.html
121 //Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
122 server.default_resource["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
124 auto web_root_path=boost::filesystem::canonical("web");
125 auto path=boost::filesystem::canonical(web_root_path/request->path);
126 //Check if path is within web_root_path
127 if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) ||
128 !equal(web_root_path.begin(), web_root_path.end(), path.begin()))
129 throw invalid_argument("path must be within root path");
130 if(boost::filesystem::is_directory(path))
132 if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
133 throw invalid_argument("file does not exist");
135 std::string cache_control, etag;
137 // Uncomment the following line to enable Cache-Control
138 // cache_control="Cache-Control: max-age=86400\r\n";
141 // Uncomment the following lines to enable ETag
143 // ifstream ifs(path.string(), ifstream::in | ios::binary);
145 // auto hash=SimpleWeb::Crypto::to_hex_string(SimpleWeb::Crypto::md5(ifs));
146 // etag = "ETag: \""+hash+"\"\r\n";
147 // auto it=request->header.find("If-None-Match");
148 // if(it!=request->header.end()) {
149 // if(!it->second.empty() && it->second.compare(1, hash.size(), hash)==0) {
150 // *response << "HTTP/1.1 304 Not Modified\r\n" << cache_control << etag << "\r\n\r\n";
156 // throw invalid_argument("could not read file");
160 auto ifs=make_shared<ifstream>();
161 ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
164 auto length=ifs->tellg();
165 ifs->seekg(0, ios::beg);
167 *response << "HTTP/1.1 200 OK\r\n" << cache_control << etag << "Content-Length: " << length << "\r\n\r\n";
168 default_resource_send(server, response, ifs);
171 throw invalid_argument("could not read file");
173 catch(const exception &e) {
174 string content="Could not open path "+request->path+": "+e.what();
175 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
179 thread server_thread([&server](){
184 //Wait for server to start so that the client can connect
185 this_thread::sleep_for(chrono::seconds(1));
188 // HttpClient client("localhost:8080");
189 // auto r1=client.request("GET", "/match/123");
190 // cout << r1->content.rdbuf() << endl;
192 // string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
193 // auto r2=client.request("POST", "/string", json_string);
194 // cout << r2->content.rdbuf() << endl;
196 // auto r3=client.request("POST", "/json", json_string);
197 // cout << r3->content.rdbuf() << endl;
199 server_thread.join();
204 void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
205 const shared_ptr<ifstream> &ifs) {
206 //read and send 128 KB at a time
207 static vector<char> buffer(131072); // Safe when server is running on one thread
208 streamsize read_length;
209 if((read_length=ifs->read(&buffer[0], buffer.size()).gcount())>0) {
210 response->write(&buffer[0], read_length);
211 if(read_length==static_cast<streamsize>(buffer.size())) {
212 server.send(response, [&server, response, ifs](const boost::system::error_code &ec) {
214 default_resource_send(server, response, ifs);
216 cerr << "Connection interrupted" << endl;