Context in GDScript

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

Our example demonstrates how to set up a simple HTTP server in GDScript. This server is useful for showing the usage of signals for controlling cancellation. Signals in GDScript are similar to the context.Context in other languages, carrying cancellation signals across different parts of your code.

extends Node

var http_server: HTTPServer
var http_request: HTTPRequest

func _ready():
    http_server = HTTPServer.new()
    http_server.listen(8090)
    http_server.connect("client_connected", self, "_on_client_connected")
    add_child(http_server)

    print("Server started on port 8090")

func _on_client_connected(id, client):
    print("server: hello handler started")
    
    # Simulate some work
    var timer = Timer.new()
    timer.set_wait_time(10)
    timer.set_one_shot(true)
    timer.connect("timeout", self, "_on_timeout", [client])
    add_child(timer)
    timer.start()
    
    # Set up cancellation
    http_request = HTTPRequest.new()
    http_request.connect("request_completed", self, "_on_request_completed")
    add_child(http_request)
    http_request.request("http://localhost:8090/cancel")

func _on_timeout(client):
    client.put_data("hello\n".to_utf8())
    client.disconnect_from_host()
    print("server: hello handler ended")

func _on_request_completed(result, response_code, headers, body):
    if response_code == HTTPClient.RESPONSE_OK:
        print("server: request canceled")
        print("server: hello handler ended")

func _exit_tree():
    http_server.stop()

In this GDScript example, we set up an HTTP server that listens on port 8090. When a client connects, we start a timer to simulate some work being done. We also set up a cancellation mechanism using another HTTP request.

To run the server:

  1. Save this script as http_server.gd.
  2. Attach it to a Node in your Godot scene.
  3. Run the scene.

To test the server, you can use a tool like curl:

$ curl localhost:8090

If you want to simulate cancellation, you can send a request to /cancel before the 10-second timeout:

$ curl localhost:8090/cancel

This will trigger the cancellation mechanism, similar to the context cancellation in the original example.

Note that GDScript and Godot don’t have a direct equivalent to Go’s context.Context. Instead, we use Godot’s signal system to achieve similar functionality. The HTTPRequest node is used to simulate the cancellation signal.