eidheim / Simple-Web-Server

A very simple, fast, multithreaded, platform independent HTTP and HTTPS server and client library implemented using C++11 and Boost.Asio. Created to be an easy way to make REST resources available from C++ applications.
MIT License
2.61k stars 751 forks source link

Need a synchronous`response->write()` #186

Closed zethon closed 6 years ago

zethon commented 6 years ago

I have a handler where I want to shut the server down once I've written a response... for example:

_server.resource["^/shutdown$"]["GET"] = 
    [&](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) 
    {
        std::stringstream stream;
        stream << "<h1>Shutting down!</h1>";
        response->write(stream);
        _server.stop();
    };

The problem is that response->write(stream); returns immediately. Is there a synchronous way of doing this?

eidheim commented 6 years ago

You can do like this:

HttpServer _server;
_server.config.port = 8080;
_server.resource["^/shutdown$"]["GET"] = [&](std::shared_ptr<HttpServer::Response> response,
                                             std::shared_ptr<HttpServer::Request> /*request*/) {
  response->write("<h1>Shutting down!</h1>"); // Write to stream
  response->send([&](const SimpleWeb::error_code & /*ec*/) { // Send stream over network
    _server.stop(); // When send has finished, successful or not, stop the server
  });
};
_server.start();
return 0;