#include "resource.h" #include #include #include #include "../../dependencies/control_system/common/protocol_commands.h" static void loadFile(const std::string& path, std::vector& content) { std::ifstream is(path, std::ios::in | std::ios::binary); if (!is) { throw std::runtime_error("File not found"); } content.clear(); for (;;) { char buf[512]; auto len = is.read(buf, sizeof(buf)).gcount(); if (len <= 0) { break; } content.insert(content.end(), buf, buf + len); } } http::resource::BasicResource::BasicResource(std::string path): path(std::move(path)) {} http::resource::StaticFileFactory::StaticFileDef::StaticFileDef(std::string path, server::mime_types::Mime type, bool allowCache): path(std::move(path)), type(type), allowCache(allowCache) { if (allowCache) { BOOST_LOG_TRIVIAL(info) << "Load static file " << this->path; loadFile(this->path, this->content); } else { BOOST_LOG_TRIVIAL(info) << "Skip loading static file " << this->path; } } http::resource::StaticFileFactory::StaticFileDef::~StaticFileDef() = default; http::resource::StaticFileFactory::StaticFileFactory() = default; void http::resource::StaticFileFactory::registerFile(const std::string &path, server::mime_types::Mime type, bool allowCache) { this->files.emplace_back(path, type, allowCache); } void http::resource::StaticFileFactory::serve(const std::string &path, server::Reply &rep) { for (auto& f: this->files) { if (f.path == path) { #ifdef USE_DEBUG if (f.allowCache) { rep.content.clear(); rep.content.insert(rep.content.end(), f.content.begin(), f.content.end()); } else { BOOST_LOG_TRIVIAL(debug) << "Reload file " << path << " (http path: " << path << ")"; loadFile(f.path, rep.content); } #else rep.content.clear(); rep.content.insert(rep.content.end(), f.content.begin(), f.content.end()); #endif rep.status = server::ok; // rep.headers.clear(); rep.headers.push_back({.name = "Content-Type", .value = server::mime_types::toString(f.type)}); if (f.allowCache) { rep.headers.push_back({.name = "Cache-Control", .value = "max-age=86400"}); // сутки, думаю хватит } return; } } } http::resource::StaticFileFactory::~StaticFileFactory() = default; http::resource::GenericResource::GenericResource(const std::string &path, respGenerator generator): BasicResource(path), generator_(std::move(generator)) {} void http::resource::GenericResource::handle(const server::Request &req, server::Reply &rep) { this->generator_(req, rep); } http::resource::GenericResource::~GenericResource() = default;