add microhttpd server

This commit is contained in:
2024-11-14 18:15:27 +03:00
parent ee34e8a72e
commit cdde340efe
12 changed files with 599 additions and 221 deletions

View File

@@ -0,0 +1,75 @@
#ifndef MICROHTTPD_SERVER_P_H
#define MICROHTTPD_SERVER_P_H
#include "pibase.h"
#include "piobject.h"
#include "pip_http_server_export.h"
struct MicrohttpdServerConnection;
class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
PIOBJECT(MicrohttpdServer)
friend struct MicrohttpdServerConnection;
public:
MicrohttpdServer();
virtual ~MicrohttpdServer();
enum class Method {
Unknown,
Get,
Head,
Post,
Put,
Delete,
Connect,
Options,
Trace,
Patch
};
struct PIP_HTTP_SERVER_EXPORT Request {
MicrohttpdServer::Method method;
PIString path;
PIByteArray body;
PIMap<PIString, PIString> headers;
PIMap<PIString, PIString> args;
};
class PIP_HTTP_SERVER_EXPORT Reply {
friend struct MicrohttpdServerConnection;
public:
void addHeader(const PIString & header, const PIString & value);
void removeHeader(const PIString & header);
void setBody(const PIByteArray & b);
void setCode(int c);
private:
void addFixedHeaders();
int code = 200;
PIByteArray body;
PIMap<PIString, PIString> headers;
};
void setWWWRoot(const PIString & path);
void setFavicon(const PIByteArray & im);
bool listen(PINetworkAddress addr);
bool listenAll(ushort port) { return listen({0, port}); }
bool isListen() const;
void stop();
void setRequestCallback(std::function<Reply(Request)> c) { callback = c; }
private:
PIByteArray getFile(PIString name);
PRIVATE_DECLARATION(PIP_HTTP_SERVER_EXPORT)
PIString www_root;
PIByteArray favicon;
std::function<Reply(Request)> callback;
};
#endif

View File

@@ -0,0 +1,33 @@
#ifndef PIHTTPSERVER_H
#define PIHTTPSERVER_H
#include "microhttpd_server_p.h"
#include "pip_http_server_export.h"
class PIP_HTTP_SERVER_EXPORT PIHTTPServer: public MicrohttpdServer {
PIOBJECT_SUBCLASS(PIHTTPServer, MicrohttpdServer)
public:
PIHTTPServer();
virtual ~PIHTTPServer();
using RequestFunction = std::function<MicrohttpdServer::Reply(const MicrohttpdServer::Request &)>;
void registerPath(const PIString & path, RequestFunction functor);
void addReplyHeader(const PIString & name, const PIString & value) { reply_headers[name] = value; }
void removeReplyHeader(const PIString & name) { reply_headers.remove(name); }
void clearReplyHeaders() { reply_headers.clear(); }
private:
struct Endpoint {
bool match(const PIStringList & in_path) const;
PIStringList path;
RequestFunction function;
};
PIMap<PIString, PIString> reply_headers;
PIMap<PIString, Endpoint> functions;
};
#endif