Skip to content

Any method to run mongoose in a single thread? #2176

@zeroxer

Description

@zeroxer

I want to start a http server in a seprate thread in my app, not the main thread. Can mongoose works fine in this way? Any example code will be helpful.

I have tried this, but it doesn't work. And I cannot open the http://127.0.0.1:8000.
I have tried use packed file in c(main.c) according to the documentation of mongoose and it works fine.

  • main.cpp
#include "mongoose.h"

const char *s_listening_url = "http://0.0.0.0:8000";

// HTTP request handler function
void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data)
{
    if (ev == MG_EV_HTTP_MSG)
    {
        struct mg_http_serve_opts opts;
        opts.root_dir = "/dist";
        opts.fs = &mg_fs_packed;
        mg_http_serve_dir(
            static_cast<struct mg_connection *>(c),
            static_cast<struct mg_http_message *>(ev_data),
            static_cast<struct mg_http_serve_opts *>(&opts));
    }
    // (void)fn_data;
}

void http_main(void)
{
    struct mg_mgr mgr;
    mg_log_set(MG_LL_INFO);
    mg_mgr_init(&mgr);
    mg_http_listen(&mgr, s_listening_url, fn, NULL);
    while (true)
        mg_mgr_poll(&mgr, 500);
    mg_mgr_free(&mgr);
}

int main() {
    std::thread http_thread(http_main);
    http_thread.detach();
   // main logic of other functions
   // ......
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions