Context in ActionScript

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

Our first example demonstrates how to use context in a simple HTTP server. HTTP servers are useful for demonstrating the usage of flash.utils.Timer for controlling cancellation. A Timer can be used to implement timeouts and cancellation signals across different parts of your application.

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.net.URLRequestMethod;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.utils.Timer;

    public class ContextExample extends Sprite {
        public function ContextExample() {
            addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        }

        private function onAddedToStage(event:Event):void {
            startServer();
        }

        private function startServer():void {
            trace("Server started");
            simulateRequest();
        }

        private function simulateRequest():void {
            trace("server: hello handler started");

            var timer:Timer = new Timer(10000, 1);
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
            timer.start();

            // Simulate cancellation after 2 seconds
            var cancellationTimer:Timer = new Timer(2000, 1);
            cancellationTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onCancellation);
            cancellationTimer.start();
        }

        private function onTimerComplete(event:TimerEvent):void {
            trace("hello");
            trace("server: hello handler ended");
        }

        private function onCancellation(event:TimerEvent):void {
            trace("server: context canceled");
            trace("server: hello handler ended");
        }
    }
}

In this ActionScript example, we simulate a server using timers. The startServer function initiates the server, and simulateRequest represents handling a request.

A Timer is used to simulate work being done by the server. It’s set to 10 seconds, similar to the original example’s time.After(10 * time.Second).

To simulate cancellation, we use another Timer set to 2 seconds. When this timer completes, it triggers the cancellation, similar to how the context’s Done() channel works in the original example.

To run this example, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be visible in the trace log or console, depending on your development environment.

Note that ActionScript doesn’t have built-in HTTP server capabilities like Go does, so this example focuses on simulating the timing and cancellation aspects of the original code. In a real-world scenario, you might use external libraries or AIR APIs for actual network operations.