Overview: HTTP Server

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}"
    

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/docs/overview/http_server.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部