From 13579acd8f0f51f2070a7db2fcd4965e97df442a Mon Sep 17 00:00:00 2001 From: Mutzi Date: Mon, 23 Oct 2023 17:33:19 +0200 Subject: [PATCH] Implemented caching for index.html --- lib/CMakeLists.txt | 2 +- src/main.cxx | 41 ++++++++++++++++++++++++++++++++--------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index a990a13..37cce15 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -2,7 +2,7 @@ add_subdirectory(spdlog-1.12.0) add_subdirectory(restbed-4.8) add_custom_command( - COMMAND ./configure.py ARGS --amalgamation --disable-shared --minimized-build --enable-modules=argon2fmt,hotp,base32,auto_rng,system_rng,tls13,certstor_system,certstor_flatfile + COMMAND ./configure.py ARGS --amalgamation --disable-shared --minimized-build --enable-modules=argon2fmt,hotp,base32,auto_rng,system_rng,tls13,certstor_system,certstor_flatfile,md5 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/Botan-3.2.0 OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/Botan-3.2.0/botan_all.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Botan-3.2.0/botan_all.h ) diff --git a/src/main.cxx b/src/main.cxx index d3366bd..d84237a 100644 --- a/src/main.cxx +++ b/src/main.cxx @@ -1,5 +1,7 @@ #include #include +#include +#include #include #include #include @@ -26,6 +28,13 @@ int main() { spdlog::default_logger()->sinks().push_back(file_sink); spdlog::set_level(spdlog::level::trace); + std::string index_etag; + { + auto md5_hash = Botan::HashFunction::create_or_throw("MD5"); + md5_hash->update(index_html_bytes); + index_etag = Botan::hex_encode(md5_hash->final()); + } + auto mrpc_resource = std::make_shared(); mrpc_resource->set_path("/mrpc"); Server server{mrpc_resource}; @@ -41,15 +50,29 @@ int main() { auto index_resource = std::make_shared(); index_resource->set_path("/"); - index_resource->set_method_handler("GET", [](const std::shared_ptr& s){ - s->yield( - 200, - index_html_bytes, - std::multimap{ - {"Content-Type", "text/html"}, - {"Content-Length", std::to_string(index_html_len)} - } - ); + index_resource->set_method_handler("GET", [&index_etag](const std::shared_ptr& s){ + auto req = s->get_request(); + if (req->get_header("If-None-Match", "") == index_etag) { + s->yield( + 304, + "", + std::multimap{ + {"Cache-Control", "no-cache"}, + {"ETag", index_etag} + } + ); + } else { + s->yield( + 200, + index_html_bytes, + std::multimap{ + {"Content-Type", "text/html"}, + {"Content-Length", std::to_string(index_html_len)}, + {"Cache-Control", "no-cache"}, + {"ETag", index_etag} + } + ); + } }); auto favicon_resource = std::make_shared();