Search code examples
c++casablancacpprest-sdk

How to keep server running (cpprestsdk - casablanca)


I am developing a REST api using Microsoft's cpprestsdk (aka casablanca) and I am having trouble keeping the server running when executing my code.

See my main.cpp here:

int main() {
    cout << "Starting Server" << endl;

    TransactionController server;
    server.setEndpoint("http://0.0.0.0:4200/api");
    server.initHandlers();

    try {
        server.openServer();
        cout << "Server listening at: " << server.getEndpoint() << endl;

        // figure out how to keep server running without this?
        while (true);
    }
    catch(exception &e) {
        cout << "--- ERROR DETECTED ---" << endl;
        cout << e.what() << endl;
    }


    // this doesn't get reached bc of the while(true)
    server.closeServer();

    return 0;
}

Additionally, for reference this is the implementation or the functions I have in my main.cpp:

pplx::task<void> TransactionController::openServer() {
    return listener.open();
}

pplx::task<void> TransactionController::closeServer() {
    return listener.close();
}

std::string TransactionController::getEndpoint() const{
    return listener.uri().to_string();
}


void TransactionController::initHandlers() {
    listener.support(methods::GET, bind(&TransactionController::handleGet, this, std::placeholders::_1));
    listener.support(methods::POST, bind(&TransactionController::handlePost, this, placeholders::_1));
}

void TransactionController::setEndpoint(const string& value) {
    listener = http_listener(value);
}

I have found a not ideal workaround of adding a

while(true);

to keep the server running until I manually halt execution.

I would like to implement this feature in a more elegant way however. I have explored the documentation online but have not been able to find the right methodology.

Any tips or pointers in the right direction would be greatly appreciated, as I have never worked with Casablanca before. Thank you for your time!


Solution

  • So I managed to figure it out by using code provided here:

    https://github.com/ivanmejiarocha/micro-service/blob/master/source/foundation/include/usr_interrupt_handler.hpp

    Here is now my new main.cpp:

    int main() {
        cout << "Starting Server" << endl;
    
        InterruptHandler::hookSIGINT();
    
        TransactionController server;
        server.setEndpoint("http://0.0.0.0:4200/api");
        server.initHandlers();
    
        try {
            server.openServer().wait();
            cout << "Server listening at: " << server.getEndpoint() << endl;
    
            InterruptHandler::waitForUserInterrupt();
    
            server.closeServer().wait();
            cout << "Shutting Down Server" << endl;
        }
        catch(exception &e) {
            cout << "--- ERROR DETECTED ---" << endl;
            cout << e.what() << endl;
        }    
    
        return 0;
    }