Microhttpd callbacks

FossilOrigin-Name: 67c555c91e7e54264b1497125b95e83fcb13e335515a494f4d11abdcde1d86a1
This commit is contained in:
nekobit 2022-10-24 21:05:35 +00:00
parent d84ac84da0
commit 34ca246998

View file

@ -28,8 +28,27 @@
#include <microhttpd.h>
#include "http/response.h"
constexpr int POSTBUFFERSIZE = 2048;
using namespace HTTP;
// Struct we define to hold onto data
struct MHDConnectionInfo
{
MHDConnectionInfo()
: data{nullptr},
processor{nullptr}
{}
~MHDConnectionInfo()
{
MHD_destroy_post_processor(processor);
}
char* data;
MHD_PostProcessor* processor;
};
namespace
{
HTTP::Request::Type str_to_method(std::string method)
@ -45,6 +64,7 @@ namespace
}
// Iterator function for POST, GET, etc.
//
enum MHD_Result gcv_iterator(void* cls, MHD_ValueKind kind,
const char* key, size_t key_len,
const char* value, size_t value_len)
@ -70,12 +90,39 @@ namespace
return MHD_YES;
}
MHD_Result gcv_iterate_post_raw(void* coninfo_cls,
enum MHD_ValueKind kind,
const char* key,
const char* filename,
const char* content_type,
const char* transfer_encoding,
const char* data,
uint64_t off,
size_t size)
{
MHDConnectionInfo* con_info = reinterpret_cast<MHDConnectionInfo*>(coninfo_cls);
return MHD_YES;
}
void request_completed (void *cls,
struct MHD_Connection *connection,
void **con_cls,
enum MHD_RequestTerminationCode toe)
{
MHDConnectionInfo* con_info = reinterpret_cast<MHDConnectionInfo*>(*con_cls);
if (NULL == con_info)
return;
delete con_info;
}
enum MHD_Result new_connection(void* cls,
MHD_Connection* conn,
const char* url,
const char* method,
const char* _method,
const char* version,
const char* upload_data,
size_t* upload_data_size,
@ -83,10 +130,24 @@ namespace
{
MicroHttpdServer* that = reinterpret_cast<MicroHttpdServer*>(cls);
MHD_Response* response;
HTTP::Request::Type method = str_to_method(_method);
enum MHD_Result ret;
// Get post data, if any
if (*con_cls)
{
if (method == HTTP::Request::Type::POST)
{
MHDConnectionInfo* con_info = new MHDConnectionInfo;
con_info->processor = MHD_create_post_processor(conn, POSTBUFFERSIZE, gcv_iterate_post_raw, con_info);
*con_cls = con_info;
return MHD_YES;
}
}
// Create generic request from args
HTTP::Request req{str_to_method(method), url};
HTTP::Request req{method, url};
// Maps to string_view
req.data = { upload_data, *upload_data_size };
@ -120,9 +181,7 @@ namespace
MicroHttpdServer::MicroHttpdServer(std::uint16_t port, std::any callback_args)
: Server(port, callback_args),
serv(nullptr)
{
}
{}
void MicroHttpdServer::start()
{
@ -132,6 +191,9 @@ void MicroHttpdServer::start()
0,
&::new_connection,
this,
MHD_OPTION_NOTIFY_CONNECTION,
request_completed,
this,
MHD_OPTION_END));
}
@ -141,6 +203,5 @@ void MicroHttpdServer::stop()
{
// Will call "destructor"
serv = nullptr;
}