Mongoose 7.8, C++ Standard 17
When uploading files with mg_http_serve_file the associated headers get baked into the file before the actual file headers, leading them to all be unreadable.
As an example, a .jpg uploaded would look like:
HTTP/1.1 304 Not Modified
Content-Length: 0000000000
����...JFIF // The actual .jpg data
Following guides, this is my event handler:
namespace fs = std::filesystem
static void evt_handler(struct mg_connection* c, int ev, void* ev_data, void* fn_data)
{
if (ev == MG_EV_HTTP_MSG)
{
struct mg_http_message* hm = (struct mg_http_message*)ev_data;
struct mg_http_serve_opts opts = {};
std::string s = hm->uri.ptr;
std::string buf = "";
int i = 0;
while (s[i] != ' ') { buf += s[i++]; }
// If requesting image
if (buf.find("/img/") != std::string::npos)
{
i = 5;
buf = "";
while (s[i] != ' ') { buf += s[i++]; }
fs::path p = fs::current_path();
fs::path z = "\\html\\img\\" + buf;
p += z;
mg_http_serve_file(c, hm, p.string().c_str(), &opts);
}
mg_http_serve_file(c, hm, "./html/index.html", &opts);
}
}
Initialization
int initServer(const char* url)
{
struct mg_mgr mongoose_manager;
mg_mgr_init(&mongoose_manager);
mg_http_listen(&mongoose_manager, url, evt_handler, NULL);
for (;;)
{
mg_mgr_poll(&mongoose_manager, 1000);
}
mg_mgr_free(&mongoose_manager);
return 0;
};
Main
int main(int argc, char const* argv[])
{
const char* url = "127.0.0.1:9080";
initServer(url);
return 0;
}
The files appear to still be valid, but the garbage data is added somewhere along the way.