This commit is contained in:
Nicholas Orlowsky 2023-10-17 13:16:31 -04:00
parent 38359bd957
commit d6eb46d310
No known key found for this signature in database
GPG key ID: BE7DF0188A405E2B
20 changed files with 178 additions and 1020295 deletions

View file

@ -4,28 +4,11 @@
class file_backend : public backend {
private:
unordered_map<string, string> file_cache;
bool cache_enabled;
unique_ptr<http_response> handle_request_nocache(http_request& req) {
string filename = req.path() == "/" ? "index.html" : req.path();
filename = "./www/" + filename;
ifstream stream(filename);
int status = 200;
if (!stream.is_open()) {
status = 404;
filename = "./error_pages/404.html";
stream = ifstream(filename);
}
stringstream buffer;
buffer << stream.rdbuf();
return make_unique<http_response>(buffer.str(), status);
}
string file_dir;
unique_ptr<http_response> handle_request_cache(http_request& req) {
string filename = req.path() == "/" ? "/index.html" : req.path();
filename = "./www" + filename;
string filename = req.path() == "/" ? "index.html" : req.path();
filename = file_dir + filename;
auto file_info = file_cache.find(filename);
int status = 200;
@ -35,7 +18,7 @@ private:
file_info = file_cache.find(filename);
}
return make_unique<http_response>(file_info->second, status);
return make_unique<http_response>(file_info->second, filename, status);
}
void populate_cache_dir(string dir) {
@ -55,18 +38,16 @@ private:
}
void populate_cache() {
populate_cache_dir("./www/");
populate_cache_dir(file_dir);
populate_cache_dir("./error_pages/");
}
public:
file_backend(bool enable_cache) : cache_enabled(enable_cache) {
if(cache_enabled) {
populate_cache();
}
file_backend(string dir = "./www") : file_dir(dir) {
populate_cache();
}
unique_ptr<http_response> handle_request(http_request& req) override {
return cache_enabled ? handle_request_cache(req) : handle_request_nocache(req);
return handle_request_cache(req);
}
};