kemal/src/kemal/dsl.cr

38 lines
1.5 KiB
Crystal
Raw Normal View History

2016-07-17 11:10:56 +00:00
# Kemal DSL is defined here and it's baked into global scope.
2017-10-06 11:53:53 +00:00
#
# The DSL currently consists of:
#
2016-12-03 22:47:09 +00:00
# - get post put patch delete options
# - WebSocket(ws)
# - before_*
# - error
2020-02-20 23:59:34 +00:00
HTTP_METHODS = %w(get post put patch delete options head)
FILTER_METHODS = %w(get post put patch delete options head all)
2015-10-23 18:33:26 +00:00
{% for method in HTTP_METHODS %}
2017-08-24 20:32:43 +00:00
def {{method.id}}(path : String, &block : HTTP::Server::Context -> _)
raise Kemal::Exceptions::InvalidPathStartException.new({{method}}, path) unless Kemal::Utils.path_starts_with_slash?(path)
2017-10-02 20:56:02 +00:00
Kemal::RouteHandler::INSTANCE.add_route({{method}}.upcase, path, &block)
end
{% end %}
2015-12-15 21:11:21 +00:00
2017-09-05 09:19:32 +00:00
def ws(path : String, &block : HTTP::WebSocket, HTTP::Server::Context -> Void)
raise Kemal::Exceptions::InvalidPathStartException.new("ws", path) unless Kemal::Utils.path_starts_with_slash?(path)
2017-10-02 20:56:02 +00:00
Kemal::WebSocketHandler::INSTANCE.add_route path, &block
2015-12-15 21:11:21 +00:00
end
2016-05-05 19:35:36 +00:00
2017-08-24 20:32:43 +00:00
def error(status_code : Int32, &block : HTTP::Server::Context, Exception -> _)
2016-05-05 19:35:36 +00:00
Kemal.config.add_error_handler status_code, &block
end
2016-12-03 22:47:09 +00:00
# All the helper methods available are:
# - before_all, before_get, before_post, before_put, before_patch, before_delete, before_options
# - after_all, after_get, after_post, after_put, after_patch, after_delete, after_options
{% for type in ["before", "after"] %}
{% for method in FILTER_METHODS %}
2017-08-24 20:32:43 +00:00
def {{type.id}}_{{method.id}}(path : String = "*", &block : HTTP::Server::Context -> _)
2016-12-03 22:47:09 +00:00
Kemal::FilterHandler::INSTANCE.{{type.id}}({{method}}.upcase, path, &block)
end
{% end %}
{% end %}