Search code examples
c++webservermongoose-web-server

Mongoose should render an html file


I observed that when the Mongoose server event handler is NULL, an HTML file (for example, localhost:8080/index.html) is rendered without any hassles at out.

Here's the code taken from the example of the Mongoose Github repo at https://github.com/cesanta/mongoose.

int main(void) {
    struct mg_server *server = mg_create_server(NULL, NULL);

    mg_set_option(server, "listening_port", "8080");

    printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
    for (;;) {
        mg_poll_server(server, 1000);
    }

    mg_destroy_server(&server);

    return 0;
}

I want to use the event handler of Mongoose to handle requests. Saw a tutorial here: https://github.com/cesanta/mongoose/blob/master/examples/post.c. The only problem is that I can't access my index.html file unless it is initialized as embedded file as shown in the code below. I want to remove the embedded file version and render the actual html file.

#include <stdio.h>
#include <string.h>
#include "mongoose.h"

static const char *html_form =   
    "<html><body>"
    "<form action=\"/handle_request\">"
        "<input type=\"text\" name=\"request_value\" /> <br/>"
    "<input type=\"submit\" />"
    "</form></body></html>";

static void send_reply(struct mg_connection *conn) {
    char value[500];

    if(strcmp(conn->uri, "/handle_request") == 0) {
        mg_get_var(conn, "request_value", value, sizeof(value));
        mg_send_header(conn, "Content-Type", "text/plain");

        mg_printf_data( conn, value );
    } if(strcmp(conn->uri, "/index.html") == 0) {
        // #######################
        //      HELP ME HERE 
        // #######################
        //  Render the html file.
        // #######################
    } else {
        mg_send_data(conn, html_form, strlen(html_form));
    }
}

static int ev_handler( struct mg_connection *conn, enum mg_event ev ) {
    if ( ev == MG_REQUEST ) {
        send_reply( conn );
        return MG_TRUE;
    } else if ( ev == MG_AUTH ) {
        return MG_TRUE;
    } else {
        return MG_FALSE;
    }
}

int main(void) {
    struct mg_server *server = mg_create_server(NULL, ev_handler);

    mg_set_option(server, "listening_port", "8080");

    printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
    for (;;) {
        mg_poll_server(server, 1000);
    }

    mg_destroy_server(&server);

    return 0;
}

Any suggestions? Thanks in advance.


Solution

    1. Set document_root option.
    2. Change // HELP ME HERE to return MG_FALSE;

    The rule of thumb is: if event handler returns MG_FALSE, then mongoose does the default action. For MG_REQUEST event the default action is to serve requested file.