yhirose/cpp-httplib

Cache response to respond to request later

Sage-of-Mirrors opened this issue · 1 comments

Hello,

I am using this library to allow an external tool to communicate with a mod running inside of a video game. However, the server on the game's side must run in a separate thread, and I have created a "mailbox" system so that the server thread can communicate with the game thread.

My question is, is there a way to stop the server from immediately sending a response to a request? For example, I have an endpoint /player_pos which should return the player's current position to the client. But since the server is not running on the game thread, it takes at least 1 frame (approx. 1/60th of a second) for the position data to become available to the server via the "mailbox." Can I somehow cache the response object provided to my GET lambda, and send the response when the position is available?

Otherwise, I may have to set up a "job" system on the tool's side using HTTP 202 Accepted.

Thanks!

Can I somehow cache the response object provided to my GET lambda, and send the response when the position is available?

No, we can't. You may be able to do it with a simple loop inside a handler. It will simply wait until a new position data becomes available, then prepare the body content and return.

Here is a pseudo code. (It may not work though...)

  svr.Get("/player_pos", [&](const Request & /*req*/, Response &res) {
    while (is_position_available == false) {
      std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    
    auto json = ...; // get the position data and convert it to JSON text.
    
    res.set_content(json, "application/json");
  });

Hope it helps!