etr / libhttpserver

C++ library for creating an embedded Rest HTTP server (and more)
GNU Lesser General Public License v2.1
882 stars 184 forks source link

[BUG] Unable to launch a webserver correctly in a while loop #328

Closed matthieu-hackwitharts closed 1 year ago

matthieu-hackwitharts commented 1 year ago

Prerequisites

Description

I'm trying to play with the library by creating a sample program that has an infinite while loop in its main function. The main goal would be to create a new webserver with the params passed on user input. Unfortunately, it seems that the webserver is not starting in this loop.

Steps to Reproduce

Sample code used :

#include <iostream>
#include <string>
#include <httpserver.hpp>

class hello_world_resource : public httpserver::http_resource {
 public:
     std::shared_ptr<httpserver::http_response> render(const httpserver::http_request&) {
         return std::shared_ptr<httpserver::http_response>(new httpserver::string_response("Hello, World!"));
     }
};

int main(){

   while(1){
        std::string input;
        std::cout << "create_webserver> ";   
                std::getline(std::cin, input);
                //parsing user input.... (port, endpoint)
                httpserver::webserver result = httpserver::create_webserver(port);
        hello_world_resource hwr;
        result.register_resource(endpoint, &hwr);
            result.start(false);

        }
}
}

Expected behavior: the webserver starts correctly, and is accessible on endpoint, address and port specified by user input.

Actual behavior: The webserver doesn't start.

Versions

Additional Information

I've noticed that the code provided above works if I declare the webserver object before the while loop (the rest of the code can be executed in the while loop without any problem). However, by doing so, the program loses its interest. I don't know whether this is a bug or an inherent feature of the library, and I'd be interested in possible solutions.

etr commented 1 year ago

You are creating the webserver object within the loop. That means that you destroy the object at each iteration. You can either store them in a variable outside the loop or allocate it dynamically.