🖥️...⌨️
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