Skip to content

Commit

Permalink
[api] Add index option to http.Directory constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
pajama-coder committed Sep 4, 2023
1 parent e01a3cb commit 00c351f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
31 changes: 28 additions & 3 deletions src/api/http.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,10 @@ Directory::Options::Options(pjs::Object *options) {
Value(options, "tarball")
.get(tarball)
.check_nullable();
Value(options, "index")
.get(index)
.get(index_list)
.check_nullable();
}

//
Expand Down Expand Up @@ -307,6 +311,21 @@ Directory::Directory(const std::string &path, const Options &options) {
} else {
m_loader = new CodebaseLoader(path);
}

if (auto a = options.index_list.get()) {
a->iterate_all(
[this](pjs::Value &v, int) {
auto s = v.to_string();
m_index_filenames.push_back(s->str());
s->release();
}
);
} else if (auto s = options.index.get()) {
m_index_filenames.push_back(s->str());
} else {
m_index_filenames.push_back("index");
m_index_filenames.push_back("index.html");
}
}

Directory::~Directory() {
Expand All @@ -326,10 +345,16 @@ auto Directory::serve(Message *request) -> Message* {
Data raw, gz, br;
if (!m_loader->load_file(path, raw)) {
if (path.back() != '/') path += '/';
path += "index.html";
if (!m_loader->load_file(path, raw)) {
return nullptr;
bool found = false;
for (const auto &s : m_index_filenames) {
auto index_path = path + s;
if (m_loader->load_file(index_path, raw)) {
path = index_path;
found = true;
break;
}
}
if (!found) return nullptr;
}
m_loader->load_file(path + ".gz", gz);
m_loader->load_file(path + ".br", br);
Expand Down
5 changes: 4 additions & 1 deletion src/api/http.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ class Directory : public pjs::ObjectTemplate<Directory> {
struct Options : public pipy::Options {
bool fs = false;
bool tarball = false;
pjs::Ref<pjs::Str> index;
pjs::Ref<pjs::Array> index_list;
Options() {}
Options(pjs::Object *options);
};
Expand Down Expand Up @@ -192,8 +194,9 @@ class Directory : public pjs::ObjectTemplate<Directory> {
Tarball m_tarball;
};

std::unordered_map<std::string, File> m_cache;
Loader* m_loader = nullptr;
std::unordered_map<std::string, File> m_cache;
std::list<std::string> m_index_filenames;

auto get_encoded_response(const File &file, pjs::Object *request_headers) -> Message*;

Expand Down

0 comments on commit 00c351f

Please sign in to comment.