简体   繁体   中英

How to use Mongoose(a http server) to serve different request?

I am a newbie in http and I am using a embedded http server called mongoose.
Using a web root in ~/web_root, I would like to do :

if uri == "/hello"
    show "hello world"
else
    show the file in web_root like index.html

I tried to use mongoose like this

  struct mg_server *server;
  server = mg_create_server(p, HttpEventHandler);
  mg_set_option(server, "document_root", "~/web_root");
  mg_set_option(server, "listening_port", "8080");

  for(;;)
    mg_poll_server(server, 1000);

and this is HttpEvenHandler

int HttpEventHandler(struct mg_connection *conn, mg_event ev) {
  if(ev == MG_AUTH)
    return MG_TRUE;
  else if(ev == MG_REQUEST) {
    if(strcmp("/hello", conn->uri) == 0) {
      mg_printf_data(conn, "%s\n", "hello world");
    }
    return MG_TRUE;
  }

// I don't know what to write here

 return MG_FALSE;
}
  else if(ev == MG_REQUEST) {
    if(strcmp("/hello", conn->uri) == 0) {
      mg_printf_data(conn, "%s\n", "hello world");
      return MG_TRUE;
    }
    return MG_FALSE;  // Let Mongoose serve the request
  }

Also, I don't think that is going to work:

mg_set_option(server, "document_root", "~/web_root");

Specify a full path, eg /home/joe/web_root .

Is that REALLY what you want to achieve?

The document states that you can configure what kind of URIs are recognized as CGI invocation by command line options like -cgi_pattern /cgi-bin/*.cgi .

Then you only need to put a CGI executable named hello which outputs "hello world" under ~/web_root and tell the Mongoose server to use it as the only possible CGI: -cgi_pattern /hello$ (I haven't tested it by myself, though)

Hm, it seems that mg_set_option() is nowhere to find any more (ver. 7.3).

The correct API call for setting the web root directory would be: mg_http_serve_dir( connection, http_event_object, options);

The last parameter "options" has a member mg_http_serve_opts::root_dir . That would be the way to specify the web root directory for serving.

From design point of view this recent approach is more flexible, allowing to serve different directories based on different endpoints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM