Context in Wolfram Language

Here’s the translation of the Go code to Wolfram Language, along with explanations in Markdown format suitable for Hugo:

In this example, we’ll demonstrate how to create a simple HTTP server and handle context cancellation in Wolfram Language. While Wolfram Language doesn’t have a direct equivalent to Go’s context.Context, we can achieve similar functionality using AbortProtect and CheckAbort.

First, let’s import the necessary packages:

Needs["WebServer`"]

Now, let’s define our handler function:

hello[request_] := Module[{response},
  Print["server: hello handler started"];
  
  (* Simulate some work *)
  AbortProtect[
    CheckAbort[
      Pause[10];
      response = HTTPResponse["hello\n"],
      (* Handle cancellation *)
      (
        Print["server: request aborted"];
        response = HTTPResponse[
          "Internal Server Error", <|"StatusCode" -> 500|>
        ];
      )
    ]
  ];
  
  Print["server: hello handler ended"];
  response
]

In this handler:

  • We print a message when the handler starts and ends.
  • We use AbortProtect and CheckAbort to simulate the behavior of Go’s context cancellation.
  • The handler waits for 10 seconds before sending a response, simulating some work.
  • If the request is aborted during this time, we catch the abort and return an error response.

Now, let’s set up and start the server:

server = WebServer[{
  HTTPServerRoute["/hello", hello]
}];

(* Start the server *)
StartWebServer[server, 8090]

This sets up a server that listens on port 8090 and handles requests to the “/hello” path.

To test the server, you can use a separate Wolfram Language kernel or a tool like curl:

$ curl localhost:8090/hello

If you let it run for 10 seconds, you’ll see:

hello

If you interrupt the request before 10 seconds (e.g., by pressing Ctrl+C), you’ll see:

Internal Server Error

And in the server logs, you’ll see:

server: hello handler started
server: request aborted
server: hello handler ended

This example demonstrates how to handle long-running operations in a web server context, allowing for cancellation if the client disconnects or the request times out. While the implementation details differ from Go, the core concept of gracefully handling cancellation remains the same.

To stop the server when you’re done, you can use:

StopWebServer[server]

This example showcases how to create a simple HTTP server in Wolfram Language with basic request cancellation handling, mirroring the functionality of the original Go example.