HTTP Server

A slightly more interesting example is an HTTP Server:

require "http/server"

server = HTTP::Server.new do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello world! The time is #{Time.local}"
end

address = server.bind_tcp 8080
puts "Listening on http://#{address}"
server.listen

The above code will make sense once you read the whole language reference, but we can already learn some things.

  • You can require code defined in other files:

    require "http/server"
    
  • You can define local variables without the need to specify their type:

    server = HTTP::Server.new(...)
    
  • The port of the HTTP server is set by using the method bind_tcp on the object HTTP::Server (the port set to 8080).

    address = server.bind_tcp 8080
    
  • You program by invoking methods (or sending messages) to objects.

    HTTP::Server.new(...)
    # ...
    Time.local
    # ...
    address = server.bind_tcp 8080
    # ...
    puts "Listening on http://#{address}"
    # ...
    server.listen
    
  • You can use code blocks, or simply blocks, which are a very convenient way to reuse code and get some features from the functional world:

    HTTP::Server.new do |context|
      # ...
    end
    
  • You can easily create strings with embedded content, known as string interpolation. The language comes with other syntax as well to create arrays, hashes, ranges, tuples and more:

    "Hello world! The time is #{Time.local}"
    

To the extent possible under law, the persons who contributed to this workhave waived
all copyright and related or neighboring rights to this workby associating CC0 with it.
https://crystal-lang.org/reference/getting_started/http_server.html