Skip to content

Http protocol support: Range and If-Modified-Since #1084

Description

@bit-garden

It would be helpful if Range and If-Modified-Since was implemented out of the box.

The range header support can probably be added in add_static_dir and have set_static_file_info_unsafe optionally have a byte offset.

Here's my current If-Modified-Since support, though it uses cpp 20 at the moment.

  /// \brief Go through the rules, upgrade them if possible, and add them to the
  /// list of rules
  void add_static_dir() {
    if (are_static_routes_added())
      return;
    auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);

    route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(
        CROW_STATIC_ENDPOINT)([static_dir_](const crow::request &req,
                                            crow::response &res,
                                            std::string file_path_partial) {
      utility::sanitize_filename(file_path_partial);
      res.set_static_file_info_unsafe(static_dir_ + file_path_partial);

      // change to use 304 response code
      if (std::filesystem::exists(static_dir_ + file_path_partial)) {
        std::filesystem::file_time_type ftime =
            std::filesystem::last_write_time(static_dir_ + file_path_partial);

        auto lastmod = format("{:%a, %d %b %Y %T} GMT",
                              std::chrono::floor<std::chrono::seconds>(ftime));

        if (lastmod == get_header_value(req.headers, "If-Modified-Since")) {
          // res 304
          res.code = 304;
        } else {
          // 200
          res.set_header("Cache-Control", "no-cache");
          res.set_header("Last-Modified", lastmod);
          // send date modified
        }
      }

      res.end();
    });
    set_static_routes_added();
  }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions