diff --git a/src/kemal/handler.cr b/src/kemal/handler.cr index 4b4e813..c5a8ac4 100644 --- a/src/kemal/handler.cr +++ b/src/kemal/handler.cr @@ -25,8 +25,7 @@ class Kemal::Handler < HTTP::Handler def process_request(request) url = request.path.not_nil! @routes.each do |route| - url.match(route.pattern as Regex) do |url_params| - request.url_params = url_params + if route.match?(request) context = Context.new(request, route) begin body = route.handler.call(context).to_s diff --git a/src/kemal/route.cr b/src/kemal/route.cr index 4a0437d..f8741b4 100644 --- a/src/kemal/route.cr +++ b/src/kemal/route.cr @@ -3,10 +3,37 @@ # what action to be done if the route is matched. class Kemal::Route getter handler - getter pattern + getter method - def initialize(@method, path, &@handler : Kemal::Context -> _) - @pattern = pattern_to_regex path + def initialize(@method, @path, &@handler : Kemal::Context -> _) + end + + def match?(request) + check_for_method_override!(request) + return nil unless request.override_method == @method + return true if request.path.not_nil!.includes?(':') && request.path.not_nil! == @path + request.path.not_nil!.match(pattern_to_regex(@path)) do |url_params| + request.url_params = url_params + return true + end + end + + # Checks if request params contain _method param to override request incoming method + def check_for_method_override!(request) + request.override_method = request.method + if request.method == "POST" + params = Kemal::ParamParser.new(self, request).parse_request + if params.has_key?("_method") && self.override_method_valid?(params["_method"]) + request.override_method = params["_method"] + end + end + end + + # Checks if method contained in _method param is valid one + def override_method_valid?(override_method) + return false unless override_method.is_a?(String) + override_method = override_method.upcase + return (override_method == "PUT" || override_method == "PATCH" || override_method == "DELETE") end private def pattern_to_regex(pattern)