2015-10-29 15:16:29 +00:00
|
|
|
# ParamParser parses the request contents including query_params and body
|
|
|
|
# and converts them into a params hash which you can within the environment
|
|
|
|
# context.
|
2015-10-28 18:38:24 +00:00
|
|
|
class Kemal::ParamParser
|
2015-11-05 10:38:06 +00:00
|
|
|
URL_ENCODED_FORM = "application/x-www-form-urlencoded"
|
|
|
|
|
2015-10-28 18:30:27 +00:00
|
|
|
def initialize(@route, @request)
|
|
|
|
@route_components = route.components
|
|
|
|
@request_components = request.path.not_nil!.split "/"
|
|
|
|
@params = {} of String => String
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse
|
|
|
|
parse_components
|
|
|
|
parse_request
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_request
|
2015-11-05 10:38:06 +00:00
|
|
|
parse_query
|
|
|
|
parse_body
|
2015-10-28 18:30:27 +00:00
|
|
|
@params
|
|
|
|
end
|
|
|
|
|
2015-11-05 10:38:06 +00:00
|
|
|
def parse_body
|
|
|
|
return unless @request.headers["Content-Type"]? == URL_ENCODED_FORM
|
|
|
|
parse_part(@request.body)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_query
|
|
|
|
parse_part(@request.query)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_part(part)
|
|
|
|
return unless part
|
|
|
|
HTTP::Params.parse(part) do |key, value|
|
|
|
|
@params[key] ||= value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2015-10-28 18:30:27 +00:00
|
|
|
def parse_components
|
|
|
|
@route_components.zip(@request_components) do |route_component, req_component|
|
|
|
|
if route_component.starts_with? ':'
|
|
|
|
@params[route_component[1..-1]] = req_component
|
|
|
|
else
|
|
|
|
return nil unless route_component == req_component
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|