Context in AngelScript
Here’s the translation of the Go code example to AngelScript, formatted in Markdown suitable for Hugo:
Our example demonstrates how to use context for controlling cancellation in an HTTP server. A context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and functions.
#include <angelscript.h>
#include <scriptbuilder/scriptbuilder.h>
#include <scriptstdstring/scriptstdstring.h>
#include <datetime/datetime.h>
#include <scriptarray/scriptarray.h>
void hello(string& in, string& out)
{
print("server: hello handler started");
// Simulate work
uint64 startTime = getSystemTime();
while (getSystemTime() - startTime < 10000) // 10 seconds
{
// Check for cancellation
if (isCancellationRequested())
{
print("server: request canceled");
out = "Internal Server Error: Request canceled";
return;
}
// Yield to allow other operations
yield();
}
out = "hello\n";
print("server: hello handler ended");
}
void main()
{
// Register the hello function with the HTTP server
registerHttpHandler("/hello", hello);
// Start the HTTP server
startHttpServer(8090);
}
In this AngelScript version:
We include necessary headers for AngelScript and some hypothetical utility libraries.
The
hello
function simulates the handler. It takes input and output strings as parameters.We use a simple loop to simulate work, checking for cancellation periodically.
The
isCancellationRequested()
function is a hypothetical function that would check if the request has been canceled.We use
yield()
to allow other operations to proceed, simulating cooperative multitasking.In the
main
function, we register the handler and start the server.
To run the server:
$ angelscript context.as &
Simulate a client request to /hello
, interrupting it shortly after starting:
$ curl localhost:8090/hello
server: hello handler started
^C
server: request canceled
server: hello handler ended
This example demonstrates how to implement cancellation in AngelScript, although the exact implementation would depend on the specific AngelScript environment and available libraries. The concept of context and cancellation is simulated using a cancellation check in a loop, which is a common pattern in single-threaded or cooperative multitasking environments.