summaryrefslogtreecommitdiff
path: root/src/send_file.cc
blob: e5bf92b8a77a6f5f308121547a5d5fb3b742175a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "common.hh"

#include "config.hh"
#include "send_file.hh"

namespace {

class SendFileImpl : public SendFile {
public:
  bool setup(Logger*, Config* config,
             std::string_view sendfile_header_name,
             std::string_view sendfile_path_name) override {
    header_ = config->get(std::string(sendfile_header_name), "");
    path_ = config->get(std::string(sendfile_path_name), "");
    return true;
  }

  std::unique_ptr<Transport::Response> create_ok_file(
      Transport* transport,
      std::filesystem::path const& full_path, std::string_view relative_path,
      std::string_view etag, std::optional<uint64_t> size) override {
    if (header_.empty()) {
      auto resp = transport->create_ok_file(full_path);
      if (!etag.empty())
        resp->add_header("ETag", std::string(etag));
      if (size.has_value())
        resp->add_header("Content-Length", std::to_string(size.value()));
      return resp;
    }

    auto resp = transport->create_ok_data("");
    std::string value = path_;
    if (relative_path.empty() || relative_path.front() != '/')
      value.push_back('/');
    value.append(relative_path);
    resp->add_header(header_, std::move(value));
    return resp;
  }

private:
  std::string header_;
  std::string path_;
};

}  // namespace

std::unique_ptr<SendFile> SendFile::create() {
  return std::make_unique<SendFileImpl>();
}