add some simple function to request and response class
Created by: manageryzy
add request->parse_post()
request->parse_cookies()
to request
add response->set_MIME
response->headers
response->set_cookie
response->send_headers
to response
this a simple demo
server.default_resource["GET"] = [&server,&token](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request)
{
try
{
auto web_root_path = std::filesystem::canonical(".");
auto path = std::filesystem::canonical(web_root_path / request->path);
//Check if path is within web_root_path
if (std::distance(web_root_path.begin(), web_root_path.end()) > std::distance(path.begin(), path.end()) ||
!std::equal(web_root_path.begin(), web_root_path.end(), path.begin()))
throw std::invalid_argument("path must be within root path");
if (std::filesystem::is_directory(path))
path /= "index.html";
auto ifs = std::make_shared<std::ifstream>();
ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate);
auto cookies = request->parse_cookies();
for (auto cookie : cookies)
{
std::cout << cookie.first << " : " << cookie.second << std::endl;
}
if (*ifs)
{
auto length = ifs->tellg();
ifs->seekg(0, std::ios::beg);
response->set_MIME(path.extension().string());
response->headers.emplace("Content-Length", std::to_string(length));
response->headers.emplace("Cache-Control", "max-age=3600");
response->set_cookie("tooken", "0", std::time(nullptr) + 1000);
response->send_headers();
default_resource_send(server, response, ifs);
}
else
throw std::invalid_argument("could not read file:" + path.string());
}
catch (const std::exception& e)
{
std::string content = "Could not open path " + request->path + ": " + e.what();
*response << "HTTP/1.1 404 Not Found\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
}
};