cpp_backend/src/handlers/GetStaticAssetHandler.cpp

40 lines
858 B
C++

#include "GetStaticAssetHandler.h"
#include <fstream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
namespace beast = boost::beast;
using namespace std;
namespace http_server
{
FileResponse GetStaticAssetHandler(const StringRequest& req)
{
string rel_path_str {req.target().begin(), req.target().end()};
fs::path base_path("./public/"s);
fs::path rel_path("."s + rel_path_str);
fs::path abs_path = fs::weakly_canonical(base_path / rel_path);
http::file_body::value_type file;
FileResponse res;
res.version(11);
if (sys::error_code ec; file.open(abs_path.string().c_str(), beast::file_mode::read, ec), ec)
{
res.result(http::status::not_found);
res.content_length(0);
}
else
{
res.result(http::status::ok);
res.body() = std::move(file);
res.prepare_payload();
}
return res;
}
}