Top Level Namespace
Defined in:
Constant Summary
-
CONTENT_FOR_BLOCKS =
Hash(String, Tuple(String, Proc(Nil))).new -
FILTER_METHODS =
["get", "post", "put", "patch", "delete", "options", "all"] of ::String -
HTTP_METHODS =
["get", "post", "put", "patch", "delete", "options"] of ::String -
Kemal DSL is defined here and it's baked into global scope. These methods are available globally in your application.
Available DSL Methods
Method Summary
-
add_handler(handler : HTTP::Handler, position : Int32)
DEPRECATED Use
usewith position parameter instead -
add_handler(handler : HTTP::Handler)
Adds given
Kemal::Handlerto handlers chain.DEPRECATED Use
useinstead - after_all(path : String = "*", &block : HTTP::Server::Context -> _)
- after_all(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_delete(path : String = "*", &block : HTTP::Server::Context -> _)
- after_delete(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_get(path : String = "*", &block : HTTP::Server::Context -> _)
- after_get(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_options(path : String = "*", &block : HTTP::Server::Context -> _)
- after_options(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_patch(path : String = "*", &block : HTTP::Server::Context -> _)
- after_patch(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_post(path : String = "*", &block : HTTP::Server::Context -> _)
- after_post(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- after_put(path : String = "*", &block : HTTP::Server::Context -> _)
- after_put(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_all(path : String = "*", &block : HTTP::Server::Context -> _)
- before_all(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_delete(path : String = "*", &block : HTTP::Server::Context -> _)
- before_delete(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_get(path : String = "*", &block : HTTP::Server::Context -> _)
- before_get(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_options(path : String = "*", &block : HTTP::Server::Context -> _)
- before_options(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_patch(path : String = "*", &block : HTTP::Server::Context -> _)
- before_patch(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_post(path : String = "*", &block : HTTP::Server::Context -> _)
- before_post(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- before_put(path : String = "*", &block : HTTP::Server::Context -> _)
- before_put(paths : Enumerable(String), &block : HTTP::Server::Context -> _)
- delete(path : String, &block : HTTP::Server::Context -> _)
-
error(status_code : Int32, &block : HTTP::Server::Context, Exception -> _)
Defines an error handler for the given HTTP status code.
-
error(status : HTTP::Status, &block : HTTP::Server::Context, Exception -> _)
Defines an error handler for the given
HTTP::Status. -
error(exception : Exception.class, &block : HTTP::Server::Context, Exception -> _)
Defines an error handler for the given exception type.
- get(path : String, &block : HTTP::Server::Context -> _)
-
gzip(status : Bool = false)
Configures an
HTTP::Server::Responseto compress the response output, either using gzip or deflate, depending on theAccept-Encodingrequest header. -
headers(env : HTTP::Server::Context, additional_headers : Hash(String, String))
Helper for easily modifying response headers.
-
log(message : String)
Logs the output via
logger.DEPRECATED Use standard library Log
-
logger(logger : Kemal::BaseLogHandler)
This is used to replace the built-in
Kemal::LogHandlerwith a custom logger.DEPRECATED Use standard library Log
-
logging(status : Bool)
Enables / Disables logging.
-
mount(path : String, router : Kemal::Router)
Mounts a router at the given path prefix.
-
mount(router : Kemal::Router)
Mounts a router without additional prefix.
- options(path : String, &block : HTTP::Server::Context -> _)
- patch(path : String, &block : HTTP::Server::Context -> _)
- post(path : String, &block : HTTP::Server::Context -> _)
-
public_folder(path : String)
Sets public folder from which the static assets will be served.
- put(path : String, &block : HTTP::Server::Context -> _)
- render_404
- render_500(context, exception, verbosity)
-
send_file(env : HTTP::Server::Context, path : String, mime_type : String | Nil = nil, *, filename : String | Nil = nil, disposition : String | Nil = nil)
Send a file with given path and base the mime-type on the file extension or default
application/octet-streammime_type. -
send_file(env : HTTP::Server::Context, data : Slice(UInt8), mime_type : String | Nil = nil, *, filename : String | Nil = nil, disposition : String | Nil = nil)
Send a file with given data and default
application/octet-streammime_type. -
serve_static(status : Bool | Hash)
Enables / Disables static file serving.
-
static_headers(&headers : HTTP::Server::Context, String, File::Info -> )
Adds headers to
Kemal::StaticFileHandler. -
use(handler : HTTP::Handler, position : Int32)
Adds a
HTTP::Handler(middleware) at a specific position in the handler chain. -
use(path : String, handler : HTTP::Handler)
Adds a
HTTP::Handler(middleware) that only runs for requests matching the path prefix. -
use(path : String, handlers : Enumerable(HTTP::Handler))
Adds multiple
HTTP::Handler(middlewares) for a specific path prefix. -
use(handler : HTTP::Handler)
Adds a
HTTP::Handler(middleware) to the handler chain. -
ws(path : String, &block : HTTP::WebSocket, HTTP::Server::Context -> )
Defines a WebSocket route.
Macro Summary
-
add_context_storage_type(type)
Extends context storage with user defined types.
-
content_for(key, file = __FILE__)
content_foris a set of helpers that allows you to capture blocks inside views to be rendered later during the request. -
halt(response)
Halts execution by closing the response.
-
halt(env, status_code = 200, response = "")
Halt execution with the current context.
-
render(filename, layout)
Render view with a layout as the superview.
-
render(filename)
Render view with the given filename.
-
yield_content(key)
Yields content for the given key if a
content_forblock exists for that key.
Method Detail
DEPRECATED Use use with position parameter instead
Adds given Kemal::Handler to handlers chain.
There are 6 handlers by default and all the custom handlers
goes between the first 5 and the last Kemal::RouteHandler.
Kemal::InitHandlerKemal::LogHandlerKemal::HeadRequestHandlerKemal::ExceptionHandlerKemal::StaticFileHandler- Here goes custom handlers
Kemal::RouteHandler
DEPRECATED Use use instead
Defines an error handler for the given HTTP status code.
error 404 do |env|
"Page not found"
end
Defines an error handler for the given HTTP::Status.
error :not_found do |env|
"Page not found"
end
Defines an error handler for the given exception type.
error MyCustomException do |env, ex|
"Error: #{ex.message}"
end
Configures an HTTP::Server::Response to compress the response
output, either using gzip or deflate, depending on the Accept-Encoding request header.
Disabled by default.
Helper for easily modifying response headers. This can be used to modify a response header with the given hash.
def call(env)
headers(env, {"X-Custom-Header" => "This is a custom value"})
end
Logs the output via logger.
This is the built-in Kemal::LogHandler by default which uses STDOUT.
DEPRECATED Use standard library Log
This is used to replace the built-in Kemal::LogHandler with a custom logger.
A custom logger must inherit from Kemal::BaseLogHandler and must implement
call(context), write(message) methods.
class MyCustomLogger < Kemal::BaseLogHandler
def call(context)
puts "I'm logging some custom stuff here."
call_next(context) # => This calls the next handler
end
# This is used from `log` method.
def write(message)
STDERR.puts message # => Logs the output to STDERR
end
end
Now that we have a custom logger here's how we use it
logger MyCustomLogger.new
DEPRECATED Use standard library Log
Mounts a router at the given path prefix.
NOTE The path must start with a /.
All routes defined in the router will be prefixed with the given path.
api = Kemal::Router.new
api.get "/users" do |env|
"users"
end
mount "/api/v1", api
# Result: GET /api/v1/users
Mounts a router without additional prefix.
api = Kemal::Router.new
api.get "/users" do |env|
"users"
end
mount api
# Result: GET /users
Sets public folder from which the static assets will be served.
By default this is /public not src/public.
Send a file with given path and base the mime-type on the file extension
or default application/octet-stream mime_type.
send_file env, "./path/to/file"
Optionally you can override the mime_type
send_file env, "./path/to/file", "image/jpeg"
Also you can set the filename and the disposition
send_file env, "./path/to/file", filename: "image.jpg", disposition: "attachment"
Send a file with given data and default application/octet-stream mime_type.
send_file env, data_slice
Optionally you can override the mime_type
send_file env, data_slice, "image/jpeg"
Also you can set the filename and the disposition
send_file env, data_slice, filename: "image.jpg", disposition: "attachment"
Enables / Disables static file serving. This is enabled by default.
serve_static false
Static server also have some advanced customization options like dir_listing and
gzip.
serve_static {"gzip" => true, "dir_listing" => false}
Adds headers to Kemal::StaticFileHandler. This is especially useful for CORS.
static_headers do |env, filepath, filestat|
if filepath =~ /\.html$/
env.response.headers.add("Access-Control-Allow-Origin", "*")
end
env.response.headers.add("Content-Size", filestat.size.to_s)
end
Adds a HTTP::Handler (middleware) at a specific position in the handler chain.
use MyHandler.new, position: 1
Adds a HTTP::Handler (middleware) that only runs for requests matching the path prefix.
use "/api", AuthHandler.new
The handler will execute for:
- Exact match:
/api - Prefix match:
/api/users,/api/posts/1
But NOT for:
/,/apiv2,/other
Adds multiple HTTP::Handler (middlewares) for a specific path prefix.
use "/api", [AuthHandler.new, RateLimiter.new, CorsHandler.new]
Adds a HTTP::Handler (middleware) to the handler chain.
The handler runs for all requests.
use MyHandler.new
Defines a WebSocket route.
NOTE The path must start with a /.
ws "/chat" do |socket, env|
socket.on_message do |msg|
socket.send "Echo: #{msg}"
end
end
Macro Detail
Extends context storage with user defined types.
class User
property name
end
add_context_storage_type(User)
content_for is a set of helpers that allows you to capture
blocks inside views to be rendered later during the request. The most
common use is to populate different parts of your layout from your view.
The currently supported engines are: ecr and slang.
Usage
You call content_for, generally from a view, to capture a block of markup
giving it an identifier:
# index.ecr
<% content_for "some_key" do %>
<chunk of="html">...</chunk>
<% end %>
Then, you call yield_content with that identifier, generally from a
layout, to render the captured block:
# layout.ecr
<%= yield_content "some_key" %>
And How Is This Useful?
For example, some of your views might need a few javascript tags and
stylesheets, but you don't want to force this files in all your pages.
Then you can put <%= yield_content :scripts_and_styles %> on your
layout, inside the tag, and each view can call content_for
setting the appropriate set of tags that should be added to the layout.
Halts execution by closing the response. Designed for use with chained response method calls.
# Example: Send a JSON error and halt immediately
halt env.status(500).json({error: "Internal Server Error"})
# Example: Immediately close and halt after rendering HTML
halt env.status(403).html("Forbidden")
NOTE For most cases that require setting a specific status code and body, prefer the alternative:
halt env, status_code: 403, response: "Forbidden"
Halt execution with the current context. Returns 200 and an empty response by default.
halt env, status_code: 403, response: "Forbidden"
Render view with a layout as the superview.
render "src/views/index.ecr", "src/views/layout.ecr"
Yields content for the given key if a content_for block exists for that key.