Context in Swift

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

Our example demonstrates the usage of URLSession for making HTTP requests and DispatchQueue for handling asynchronous operations in Swift. This is similar to how context.Context is used for controlling cancellation in other languages.

import Foundation

func hello(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
    print("server: hello handler started")
    defer { print("server: hello handler ended") }

    // Create a URLSession for the request
    let session = URLSession.shared

    // Create a data task
    let task = session.dataTask(with: request) { (data, response, error) in
        // Simulate some work the server is doing
        DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
            if let error = error {
                print("server: \(error.localizedDescription)")
                completionHandler(nil, nil, error)
            } else {
                let responseString = "hello\n"
                completionHandler(responseString.data(using: .utf8), response, nil)
            }
        }
    }

    // Start the task
    task.resume()
}

func main() {
    // Create a URL
    guard let url = URL(string: "http://localhost:8090/hello") else {
        print("Invalid URL")
        return
    }

    // Create a request
    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    // Call the hello function
    hello(request: request) { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
        } else if let data = data, let responseString = String(data: data, encoding: .utf8) {
            print("Response: \(responseString)")
        }
    }

    // Keep the main thread running
    RunLoop.main.run()
}

main()

To run the server:

$ swift run

To simulate a client request, you can use curl in another terminal:

$ curl http://localhost:8090/hello

If you want to cancel the request, you can use Ctrl+C in the terminal where you’re running the Swift program.

This Swift code demonstrates how to create a simple HTTP server and handle requests asynchronously. It uses URLSession for network operations and DispatchQueue for asynchronous execution, which are analogous to the context and goroutine concepts in other languages.

The hello function simulates a long-running operation by delaying the response for 10 seconds. In a real-world scenario, this could represent some intensive work the server needs to do.

The main function sets up the server and keeps it running. In a more complex application, you might use a framework like Vapor or Kitura for more robust server functionality.

Remember that Swift on the server is still an evolving field, and the exact implementation might vary depending on the server-side Swift framework you choose to use.