Http Server in Crystal
Here’s the translation of the HTTP Server example from Go to Crystal, formatted in Markdown suitable for Hugo:
Our HTTP server example demonstrates how to create a basic server using the http/server
module in Crystal.
require "http/server"
# A fundamental concept in HTTP servers is handlers. In Crystal,
# we define handlers as blocks or procs that take an HTTP::Server::Context
# as an argument.
# This handler responds with a simple "hello" message
hello_handler = ->(context : HTTP::Server::Context) do
context.response.content_type = "text/plain"
context.response.print "hello\n"
end
# This handler reads all the HTTP request headers and echoes them
# into the response body
headers_handler = ->(context : HTTP::Server::Context) do
context.response.content_type = "text/plain"
context.request.headers.each do |name, values|
values.each do |value|
context.response.print "#{name}: #{value}\n"
end
end
end
# Create a new HTTP server
server = HTTP::Server.new do |context|
case context.request.path
when "/hello"
hello_handler.call(context)
when "/headers"
headers_handler.call(context)
else
context.response.status_code = 404
context.response.print "Not Found\n"
end
end
# Start the server
address = server.bind_tcp 8090
puts "Listening on http://#{address}"
server.listen
To run the server:
$ crystal run http_server.cr
Listening on http://0.0.0.0:8090
You can then access the /hello
route:
$ curl localhost:8090/hello
hello
This example showcases how to set up a basic HTTP server in Crystal. We define handler functions (as procs) that process incoming requests and generate responses. The server listens on port 8090 and routes requests to the appropriate handler based on the request path.
Crystal’s HTTP server implementation provides a simple and efficient way to create web servers, similar to other modern programming languages. The HTTP::Server
class and the HTTP::Server::Context
object make it easy to handle requests and generate responses.