Chuyển đến nội dung

Bài 31 · Shards and Web

Building an HTTP Server in Crystal

Build web servers in Crystal with HTTP::Server, request and response contexts, handler chains, simple routing, status codes, plus a look at Kemal, with Ruby stand-ins.

Crystal's standard library includes a fast HTTP server, HTTP::Server, and every connection is handled by its own fiber. That is why even a small Crystal web app can serve many thousands of requests per second on one core. In this lesson you will build a server from the standard library, see how handlers chain together, and then meet Kemal, the most popular small web framework.

A web server cannot run on this site's Crystal side (there is no Crystal compiler), so the Crystal listings are read-only. The Ruby stand-ins reproduce the same structure: a context object, a handler chain and a router, and one demo runs a real server on the loopback address inside the sandbox.

The smallest server

CRYSTAL
require "http/server"

server = HTTP::Server.new do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello from Crystal! You asked for #{context.request.path}"
end

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

The block receives an HTTP::Server::Context. It holds two objects: context.request (method, path, query, headers, body) and context.response (status, headers, and an IO you write the body to). Whatever you print becomes the response. server.listen blocks, accepting connections and spawning a fiber for each (see Fibers and spawn).

Routing by hand

A basic router is a case on the method and path:

CRYSTAL
server = HTTP::Server.new do |context|
  request  = context.request
  response = context.response

  case {request.method, request.path}
  when {"GET", "/"}
    response.print "Home"
  when {"GET", "/health"}
    response.content_type = "application/json"
    response.print %({"status":"ok"})
  when {"POST", "/echo"}
    response.print request.body.try(&.gets_to_end) || ""
  else
    response.status = :not_found
    response.print "Not found: #{request.path}"
  end
end

Matching on a tuple {method, path} keeps the code flat. Use response.status = :not_found (or HTTP::Status::NOT_FOUND) for non-200 answers. Query strings are available through request.query_params["name"]?, and HTTP::Params parses form bodies.

Ruby Ruby stand-in: a router over a fake context

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Handler chains (middleware)

For cross-cutting jobs (logging, error pages, compression, static files, authentication) the server accepts a list of handlers. Each handler does something, then calls call_next(context) to pass on to the next one:

CRYSTAL
class Timer
  include HTTP::Handler

  def call(context : HTTP::Server::Context)
    start = Time.utc
    call_next(context)
    elapsed = Time.utc - start
    puts "#{context.request.method} #{context.request.path} #{elapsed.total_milliseconds.round(2)} ms"
  end
end

server = HTTP::Server.new([
  HTTP::ErrorHandler.new,   # turns exceptions into a 500 page
  HTTP::LogHandler.new,     # access log
  Timer.new,
  HTTP::StaticFileHandler.new("./public"),
]) do |context|
  context.response.print "dynamic page"   # runs last, if no handler answered
end

The chain is a linked list: ErrorHandler wraps LogHandler wraps Timer, and so on. A handler may stop the chain by not calling call_next, for example to answer 401 for a missing token.

Ruby Ruby stand-in: a middleware chain

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Reading input and sending JSON

CRYSTAL
require "json"

server = HTTP::Server.new do |context|
  if context.request.path == "/sum"
    a = context.request.query_params["a"]?.try(&.to_i?) || 0
    b = context.request.query_params["b"]?.try(&.to_i?) || 0
    context.response.content_type = "application/json"
    {sum: a + b}.to_json(context.response)
  end
end

to_json(io) writes straight into the response stream without building a string first. Parsing and generating JSON is covered in JSON and YAML. Always validate input: to_i? returns nil for text that is not a number, which avoids exceptions from bad requests.

Try a real server (Ruby, loopback)

The next stand-in starts an actual HTTP server in the sandbox on 127.0.0.1, calls it from the same program, and stops it. It uses a plain TCPServer and the Net::HTTP client.

Ruby Ruby stand-in: a real loopback server

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Kemal in a nutshell

Writing routers by hand gets tedious. Kemal is a Sinatra-style framework (a shard, see Shards and Dependencies) built on top of HTTP::Server:

CRYSTAL
require "kemal"

get "/" do
  "Hello Kemal"
end

get "/users/:id" do |env|
  id = env.params.url["id"]
  env.response.content_type = "application/json"
  {id: id, name: "User #{id}"}.to_json
end

post "/notes" do |env|
  title = env.params.json["title"].as(String)
  env.response.status_code = 201
  "created #{title}"
end

before_all do |env|
  puts "#{env.request.method} #{env.request.path}"
end

Kemal.run

Other frameworks include Lucky (a type-safe, batteries-included full-stack framework), Amber (Rails-like) and Athena (a component-based framework). The choice depends on size: the standard library for tiny services, Kemal for APIs, Lucky for large applications.

Deployment notes

Compile with crystal build --release src/app.cr and ship the single binary. Bind to 0.0.0.0 inside a container, read the port from ENV["PORT"], and put a reverse proxy such as Nginx in front for TLS. Use Signal::INT.trap { server.close } for a clean shutdown.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does an HTTP::Server block receive?

    context.request describes the incoming request; context.response is where you write the reply.
  2. 2. How does one handler pass control to the next?

    call_next invokes the rest of the chain; skipping it ends the chain early.
  3. 3. How do you send a 404?

    response.status = :not_found (or HTTP::Status::NOT_FOUND) sets the code before the body.
  4. 4. Why can Crystal serve many connections with one thread?

    Waiting on a socket is a yield point, so other fibers run in the meantime.

Summary

  • HTTP::Server.new { |context| ... } handles requests; each connection gets a fiber.
  • Route with case {method, path} or use Kemal, Lucky, Amber or Athena.
  • Handlers form a chain; call_next continues it.
  • to_json(response) streams JSON; validate input with to_i?-style methods.
  • Ship a single compiled binary behind a reverse proxy.

Next: JSON and YAML

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.