Files
pip/libs/http_server/pihttpserver.cpp
2024-11-14 18:15:27 +03:00

51 lines
1.1 KiB
C++

#include "pihttpserver.h"
#include "piliterals_string.h"
PIHTTPServer::PIHTTPServer() {
setRequestCallback([this](const MicrohttpdServer::Request & r) -> MicrohttpdServer::Reply {
MicrohttpdServer::Reply rep;
rep.setCode(404);
auto in_path = r.path.split("/");
in_path.removeAll("");
auto it = functions.makeReverseIterator();
while (it.next()) {
if (it.value().function) {
if (it.value().match(in_path)) {
rep.setCode(200);
rep = it.value().function(r);
break;
}
}
}
auto hit = reply_headers.makeIterator();
while (hit.next())
rep.addHeader(hit.key(), hit.value());
return rep;
});
}
PIHTTPServer::~PIHTTPServer() {
stop();
}
void PIHTTPServer::registerPath(const PIString & path, RequestFunction functor) {
auto & ep(functions[path]);
ep.path = path.split("/");
ep.function = functor;
ep.path.removeAll("");
}
bool PIHTTPServer::Endpoint::match(const PIStringList & in_path) const {
if (in_path.size() != path.size()) return false;
for (int i = 0; i < path.size_s(); ++i) {
if (path[i] == "*"_a) continue;
if (path[i] != in_path[i]) return false;
}
return true;
}