Context in Kotlin
Here’s the translation of the Go code example to Kotlin, formatted in Markdown suitable for Hugo:
In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of CoroutineContext
for controlling cancellation. A CoroutineContext
carries job, dispatchers, and other coroutine-scoped values across API boundaries and coroutines.
In this Kotlin example, we’re using the Ktor framework to set up a simple HTTP server. The CoroutineContext
in Kotlin is analogous to the context.Context
in Go, providing a way to manage coroutine lifecycles and cancellation.
We define a route handler for “/hello” using Ktor’s DSL.
Inside the handler, we use
withTimeout
to set a 10-second timeout for the operation. This is similar to theselect
statement with a timeout in the Go example.We simulate some work by using
delay(5000)
(5 seconds).If the operation completes within the timeout, we respond with “hello\n”.
If a
TimeoutCancellationException
is caught (equivalent to the context being done in Go), we log the error and respond with an Internal Server Error.We use
println
for logging, which is not ideal for production but works for this example.In the
main
function, we start the server on port 8090.
To run the server:
To simulate a client request to /hello
, you can use curl:
If you wait for the full 10 seconds, you’ll see the “hello” response. If you interrupt the curl command before that (e.g., with Ctrl+C), you’ll see the timeout error logged on the server side.
This Kotlin version demonstrates similar concepts of context and cancellation as the original example, adapted to Kotlin’s coroutine-based concurrency model.