Shutdown idle HttpSockets, serve a complete website, etc

This commit is contained in:
Alex Hultman
2018-08-05 01:03:50 +02:00
parent 20f0a2debe
commit eb7a73651f
5 changed files with 85 additions and 10 deletions
+56 -3
View File
@@ -1,5 +1,8 @@
#include "uWS.h"
#include <fstream>
#include <sstream>
std::string buffer;
int connections = 0;
@@ -12,6 +15,34 @@ void respond(T *s) {
#define USE_SSL
#include <map>
std::string_view getFile(std::string_view file) {
static std::map<std::string_view, std::string_view> cache;
auto it = cache.find(file);
if (it == cache.end()) {
std::cout << "Did not have file: " << file << std::endl;
std::ifstream fin("rocket_files/" + std::string(file), std::ios::binary);
std::ostringstream oss;
oss << fin.rdbuf();
char *cachedFile = (char *) malloc(oss.str().size());
memcpy(cachedFile, oss.str().data(), oss.str().size());
char *key = (char *) malloc(file.length());
memcpy(key, file.data(), file.length());
cache[std::string_view(key, file.length())] = std::string_view(cachedFile, oss.str().size());
return getFile(file);
} else {
return it->second;
}
}
int main(int argc, char **argv) {
// 50 mb for huge
@@ -31,9 +62,31 @@ int main(int argc, char **argv) {
// todo: add timeouts and socket shutdown!
app.onGet("/", [](auto *s, auto *req, auto *args) {
s->writeStatus("200 OK")->writeHeader("Content-type", "text/html; charset=utf-8")->end("<h1>Welcome to µWebSockets v0.15!</h1>");
}).onGet("/tiny", [](auto *s, auto *req, auto *args) {
auto serve = [](auto *s, auto *req, auto *args) {
//std::cout << "URL: " << req->getUrl() << std::endl;
s->writeStatus("200 OK");
std::string_view file;
if (args->size() != 2) {
file = getFile("rocket.html");
} else {
file = getFile((*args)[1]);
std::string_view name = (*args)[1];
if (name.length() > 4 && name.substr(name.length() - 4) == ".svg") {
s->writeHeader("Content-type", "image/svg+xml");
}
}
/*writeHeader("Content-type", "text/html; charset=utf-8")->*/s->write([file](int offset) {
return std::string_view(file.data() + offset, file.size() - offset);
}, file.size());
};
app.onGet("/", serve).onGet("/:folder/:file", serve).onGet("/tiny", [](auto *s, auto *req, auto *args) {
respond<512>(s);
}).onGet("/small", [](auto *s, auto *req, auto *args) {
respond<4096>(s);