Server & Middleware
Starting the server
Runcobo.startRuncobo.start binds the socket, logs the address and blocks until the process receives SIGINT or SIGTERM.
Options
| Argument | Environment variable | Default |
|---|---|---|
host: | HOST | "0.0.0.0" |
port: | PORT | 3000 |
reuse_port: | REUSE_PORT (true/false) | false |
cert: | CERT | nil |
key: | KEY | nil |
handlers: | — | Runcobo::Server.default_handlers |
proxy_config: | — | trusts no proxies (see Proxies) |
shutdown_timeout: | — | 30.seconds |
Arguments override environment variables:
Runcobo.start(host: "127.0.0.1", port: 8080)TLS
Set both a certificate chain and a private key to serve HTTPS directly:
CERT=certs/server.crt KEY=certs/server.key ./bin/serverSetting only one of them is an error. In most deployments TLS terminates at a load balancer instead — see Proxies.
Multiple processes
To run several processes on the same port — one per CPU core, say — start each with REUSE_PORT=true. The operating system then balances incoming connections between them.
Graceful shutdown
On SIGINT or SIGTERM, Runcobo stops accepting connections, rejects requests that arrive on open connections with 503, and waits up to shutdown_timeout for in-flight requests to finish. Requests still running after that are reported in the log.
Handlers
Runcobo is built on Crystal's HTTP::Server. Each request passes through a chain of HTTP::Handlers. The default chain, Runcobo::Server.default_handlers, is:
LogHandlerErrorHandlerRouteHandlerRouteNotFoundHandlerPass your own list to change it. Order matters — a handler only sees requests the handlers before it pass on:
Runcobo.start(handlers: [
Runcobo::LogHandler.new,
Runcobo::ErrorHandler.new,
HTTP::CompressHandler.new, # from Crystal's stdlib
Runcobo::StaticFiles.new("/assets", directory: "public"),
Runcobo::RouteHandler.new,
Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)Two handlers are always added in front of your list by the server: one that tracks in-flight requests for graceful shutdown, and one that resolves client information.
Custom handlers
A handler is any class that includes HTTP::Handler:
class CorsHandler
include HTTP::Handler
def call(context)
context.response.headers["Access-Control-Allow-Origin"] = "https://app.example.com"
if context.request.method == "OPTIONS"
context.response.status_code = 204
return
end
call_next(context)
end
endUse handlers for cross-cutting concerns that apply to every request. Use filters for concerns that belong to specific actions.
Dependency injection
Dependencies — the database store, settings, clients for external services — travel on the request context. They're created once in main.cr, set on every request's HTTP::Server::Context by your route handler, and read back where they're needed. Nothing is global.
Declare a property on the context for each dependency:
record Blog::Settings, public_base_url : String
class HTTP::Server::Context
property! blog_store : Blog::Store::Queries
property! blog_settings : Blog::Settings
endSet them in build_action, which Runcobo::RouteHandler calls to create the action for each request:
module Blog
class RouteHandler < Runcobo::RouteHandler
def initialize(@store : Store::Queries, @settings : Settings)
end
protected def build_action(action_class : Runcobo::Action.class, context : HTTP::Server::Context) : Runcobo::Action
context.blog_store = @store
context.blog_settings = @settings
super
end
end
endGive actions short accessors in the base action:
abstract class Blog::BaseAction < ::BaseAction
protected def store : Blog::Store::Queries
context.blog_store
end
protected def settings : Blog::Settings
context.blog_settings
end
endCreate them once in main.cr:
require "./app"
settings = Blog::Settings.new(public_base_url: ENV["PUBLIC_BASE_URL"])
Blog::Store.open(ENV["DATABASE_URL"]) do |store|
Runcobo.start(handlers: [
Runcobo::LogHandler.new,
Runcobo::ErrorHandler.new,
Blog::RouteHandler.new(store, settings),
Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)
endWhy the context rather than the action? Everything that handles the request can reach it — actions, but also middleware that runs after the route handler and error-rendering code. Each dependency is typed, created once and visible in main.cr, and specs build the handler with their own values.
Using Runcobo::Server directly
Runcobo.start is a shortcut. For more control — binding a random port in tests, for example — build the server yourself:
server = Runcobo::Server.new(handlers: handlers, proxy_config: proxy_config)
server.port = 4000
server.listen # blocksHandlers can be replaced with server.handlers = [...] until the server binds its socket.