Here’s the translation of the Go code to Objective-C, formatted in Markdown suitable for Hugo:
Our first example demonstrates how to create a simple HTTP server and handle context cancellation. This is useful for controlling cancellation and managing request-scoped values across API boundaries and threads.
In this Objective-C version, we’ve created a simple server that listens on localhost:8090. The HelloHandler class simulates a long-running operation that takes 10 seconds to complete.
To run the server:
To simulate a client request and cancellation:
Note that Objective-C doesn’t have a direct equivalent to Go’s context.Context. Instead, we’ve used NSURLSession and its cancellation mechanism to achieve similar functionality. The dataTaskWithRequest:completionHandler: method can be cancelled, which will trigger an error with domain NSURLErrorDomain and code -999 (cancelled).
This example demonstrates how to handle long-running operations and cancellation in Objective-C, which is conceptually similar to using contexts in Go for managing request lifecycles and cancellation.