Context in C++

Here’s the translation of the Go code to C++, formatted in Markdown for Hugo:

Our example demonstrates the usage of context for controlling cancellation in an HTTP server. A context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and threads.

#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <httplib.h>

void hello(const httplib::Request& req, httplib::Response& res) {
    std::cout << "server: hello handler started" << std::endl;

    // Simulate some work
    auto start = std::chrono::steady_clock::now();
    while (std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) {
        if (req.is_cancelled()) {
            std::cout << "server: request cancelled" << std::endl;
            res.status = 500;
            res.set_content("Internal Server Error", "text/plain");
            std::cout << "server: hello handler ended" << std::endl;
            return;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    res.set_content("hello\n", "text/plain");
    std::cout << "server: hello handler ended" << std::endl;
}

int main() {
    httplib::Server svr;

    svr.Get("/hello", hello);

    std::cout << "Server starting on port 8090..." << std::endl;
    svr.listen("localhost", 8090);
}

In this C++ version, we’re using the httplib library to create a simple HTTP server. The context concept from Go is simulated using the is_cancelled() method provided by httplib.

To run the server:

$ g++ -std=c++17 context_example.cpp -o context_example
$ ./context_example &

To simulate a client request to /hello, you can use curl in another terminal. If you want to cancel the request, you can use Ctrl+C:

$ curl localhost:8090/hello
server: hello handler started
^C
server: request cancelled
server: hello handler ended

In this C++ version, we’re checking for cancellation in a loop while simulating work. If the request is cancelled, we set an error status and return early. This mimics the behavior of the Go example, where the context’s Done() channel is used to signal cancellation.

Note that the exact behavior and timing might differ slightly from the Go version due to differences in how C++ and the httplib library handle threading and cancellation.