Older/Server/Live2dBackend.cpp

49 lines
2.4 KiB
C++
Raw Normal View History

2024-10-23 19:53:51 +08:00
#include "Live2dBackend.h"
#include "Application.h"
#include "HttpSession.h"
#include "ServiceLogic.h"
#include <boost/url/url_view.hpp>
Live2dBackend::Live2dBackend() {
using namespace Amass;
auto application = Singleton<Application>::instance();
application->insertUrl("/api/v1/live2d/{path*}", [this, live2dModelsRoot{application->getLive2dModelsRoot()}](
HttpSession &session, const Application::Request &request,
const boost::urls::matches &matches) {
using namespace boost::beast;
boost::urls::url_view view(request.target());
auto target = view.path();
LOG(info) << target;
if (target.find("..") != boost::beast::string_view::npos) {
session.reply(ServiceLogic::badRequest(request, "Illegal request-target"));
return;
}
std::string path = ResponseUtility::pathCat(live2dModelsRoot, matches["path"]);
if (target.back() == '/') path.append("index.html");
if (std::filesystem::is_directory(path)) path.append("/index.html");
boost::beast::error_code ec;
http::file_body::value_type body;
body.open(path.c_str(), boost::beast::file_mode::scan, ec);
if (ec == boost::beast::errc::no_such_file_or_directory) {
std::ostringstream oss;
oss << "The resource '" << target << "' was not found.";
LOG(error) << oss.str();
session.errorReply(request, http::status::not_found, oss.str());
return;
} else if (ec) {
session.reply(ServiceLogic::serverError(request, ec.message()));
return;
}
auto const size = body.size();
http::response<http::file_body> res{std::piecewise_construct, std::make_tuple(std::move(body)),
std::make_tuple(http::status::ok, request.version())};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, ResponseUtility::mimeType(path));
2024-10-23 21:04:59 +08:00
// res.set(http::field::access_control_allow_origin, "*");
2024-10-23 21:35:32 +08:00
res.set(http::field::cache_control, "max-age=2592000");
res.set(http::field::expires, "Fri, 22 Nov 2124 13:30:28 GMT");
2024-10-23 19:53:51 +08:00
res.content_length(size);
res.keep_alive(request.keep_alive());
session.reply(std::move(res));
});
}