HTTP Server

A slightly more interesting example is an HTTP Server:

require "http/server"

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

puts "Listening on http://127.0.0.1:8080"
server.listen

The above code will make sense once you read the whole documentation, 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 ...
    
  • You program by invoking methods (or sending messages) to objects.

      HTTP::Server.new(8080) ...
      ...
      Time.now
      ...
      puts "Listening on http://127.0.0.1:8080"
      ...
      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(8080) 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.now}"
    

results matching ""

    No results matching ""