module

Kemal::HandlerInterface

Inherits HTTP::Handler

Kemal::HandlerInterface provides helpful methods for use in middleware creation

More specifically, only, only_match?, exclude, exclude_match? allows one to define the conditional execution of custom handlers.

By default, only / exclude match a single HTTP method (GET) and an exact path. Pass "*" as the method to match all methods, and end a path with "/*" for prefix matching (same rules as PathHandler).

A HEAD request with no HEAD route of its own is served by the GET route, so it matches a GET rule as well as a HEAD rule - the scope follows the handler that runs, without dropping the request method.

For middleware that should run for an entire path subtree on every method, prefer use "/admin", MyHandler.new instead of only.

To use, simply include it within your type.

It is an implementation of HTTP::Handler and can be used anywhere that requests an HTTP::Handler type.

Constants

ALL_METHODS = "*"

Public marker for "match every HTTP method" in only / exclude.

Instance methods

exclude_match?(env : HTTP::Server::Context)

Processes the path based on exclude paths which is a Array(String). If the path is not found on exclude conditions the handler will continue processing. If the path is found in exclude conditions it'll stop processing and will pass the request to next handler.

However this is not done automatically. All handlers must inherit from Kemal::Handler.

class ExcludeHandler < Kemal::Handler
  exclude ["/"]

  def call(env)
    return call_next(env) if exclude_match?(env)
    puts "If the path is not / i will be doing some processing here."
  end
end
Source
only_match?(env : HTTP::Server::Context)

Processes the path based on only paths which is a Array(String). If the path is not found on only conditions the handler will continue processing. If the path is found in only conditions it'll stop processing and will pass the request to next handler.

However this is not done automatically. All handlers must inherit from Kemal::Handler.

class OnlyHandler < Kemal::Handler
  only ["/"]

  def call(env)
    return call_next(env) unless only_match?(env)
    puts "If the path is / i will be doing some processing here."
  end
end
Source

Macros

exclude(paths, method = "GET")

Excludes the handler from the given paths.

Defaults to exact path match for GET only. Use "*" as method to match all HTTP methods. Paths ending with "/*" match that prefix.

exclude ["/public"]
exclude ["/assets/*"], "*"
Source
only(paths, method = "GET")

Restricts the handler to the given paths.

Defaults to exact path match for GET only. Use "*" as method to match all HTTP methods. Paths ending with "/*" match that prefix (e.g. "/admin/*" matches /admin and /admin/users).

only ["/admin"]         # GET /admin
only ["/admin"], "POST" # POST /admin
only ["/admin"], "*"    # any method, exact /admin
only ["/admin/*"], "*"  # any method under /admin
Source