How to detect when THttpServer fails to start?


How do I detect that THttpServer failed to start and is not actually working? For example, I call new THttpServer(“http:127.0.0.1:80?cors”) and as expected, it fails, but all I get is an error message printed to the terminal (Error in THttpEngine::Log: cannot bind to 127.0.0.1:80: 13 (Permission denied)). I would like to detect this failure and stop my application (since it is not actually working). I see that deep down set_ports_option() in civetweb.c sets so.sock to INVALID_SOCKET and returns 0, how is this error condition propagated to THttpServer level?

The error code path seems to be:
bind() syscall fails
set_ports_option() returns 0
mg_start2() returns NULL
mg_start() returns NULL
TCivetweb::Create() returns kFalse
THttpEngine::Create() returns kFalse
THttpServer::CreateEngine() returns fFalse, adds nothing to fEngines
THttpServer::ctor ignores the error return from CreateEngine(). WTH!

This works:
if (httpPort) {
#ifdef HAVE_THTTP_SERVER
char str[256];
snprintf(str, sizeof(str), “http:127.0.0.1:%d?cors”, httpPort);
THttpServer *s = new THttpServer(str);
if (!s->IsAnyEngine()) {
fprintf(stderr,“ERROR: Cannot start web server on http port %d, see previous error message.\n”, httpPort);
exit(1);
}

Hi @dd1,

thank you for your question. Maybe @linev could help?

Cheers,

Marta

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.

Hi,

You can use CreateEngine method of THttpServer. Like:

auto serv = new THttpServer("");
if (!serv->CreateEngine("http:127.0.0.1:80?cors"))
   printf("Fail to start server on port 80\n");

Regards,
Sergey

P.S. Sorry for some delay.