Context in Crystal
Here’s the translation of the Go code to Crystal, formatted in Markdown suitable for Hugo:
Our first example demonstrates how to use HTTP::Server
and HTTP::Handler
to create a simple HTTP server. This server uses Channel
for controlling cancellation, which is similar to the context.Context
concept in other languages. A Channel
can carry signals and values across different fibers (Crystal’s lightweight threads).
In this Crystal version:
We define a
HelloHandler
class that implements theHTTP::Handler
interface.Inside the
call
method, we use aChannel
to simulate work and potential cancellation.We use
select
to wait for either the work to complete or the request to be closed (simulating cancellation).The
spawn
keyword is used to create a new fiber, similar to a goroutine in other languages.We use Crystal’s built-in logging facility instead of
fmt.Println
.In the
main
function, we set up the HTTP server with our custom handler and start listening on port 8090.
To run the server:
Simulate a client request to /hello
, pressing Ctrl+C shortly after starting to signal cancellation:
This example demonstrates how Crystal can handle concurrent operations and manage cancellation in a web server context, similar to the original example but using Crystal’s idiomatic approaches and built-in HTTP server capabilities.