Calling functions from mongoose begin_request_handler callback

380 Views Asked by At

Currently I'm working on an application which embeds the mongoose webserver. In some cases, I have to call additional functions inside the begin_request_handler to create the desired HTTP header. During this, I realized that theses functions are called after the request handler is done. For example:

void test() {
    printf("HELLO");
}   

static int begin_request_handler(struct mg_connection *conn) {
    test();
    const struct mg_request_info *request_info = mg_get_request_info(conn);
    ...
    return 1;
}

Here the HELLO is getting printed right after the browser closes the tcp connection. Is there even a way to call functions from inside the callbacks? Or am I just missing something?

2

There are 2 best solutions below

0
On
  1. If you want to create the desired HTTP header. Then the function you mentioned above (begin_request_handler) may not be the correct approach. Look into the structure mg_request_info which is field in structure mg_connection. Here the name and value of headers is set. I think these structures are populated at the very start after connection establishment. Also look at pull() and read(). These are ground-level function where all data is set.

  2. And yes there is a way to call functions from callbacks.You can write your own callback and make callback function to point in struct of mg_context to make it point to your callback. and then in handle_request() you can call it appropriately. You can add it to struct mg_callbacks in mongoose.h

Example:

memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request => begin_request_handler;

//place your function in place of begin_request_handler
// Start the web server.

ctx = mg_start(&callbacks, NULL, options);

Please specify any more details you maybe interested in.

0
On

Well, got it. I got confused by the printf() buffers in stdout. The methods ARE called at the right time, yet the results aren't shown. Thank anyways.