require 'pry' class Router def initialize @routes = [] end def call(env) path = env["REQUEST_PATH"] method = env["REQUEST_METHOD"] @routes.each do |route| next if method != route[:method] params = match_route(path, route[:path]) if params return respond_html(route[:block].call(params)) end end respond_html("not found", status: 404) end def match_route(incoming_path, path) params = {} incoming_parts = incoming_path.split("/") path_parts = path.split("/") incoming_parts.each_with_index do |incoming_part, index| path_part = path_parts[index] if path_part&.start_with?(":") params[path_part[1..-1]] = incoming_part else if path_part != incoming_part return false end end end params end def get(path, &block) @routes.push({ method: "GET", path: path, block: block }) end def post(path, &block) @routes.push({ method: "POST", path: path, block: block }) end def put(path, &block) @routes.push({ method: "PUT", path: path, block: block }) end def delete(path, &block) @routes.push({ method: "DELETE", path: path, block: block }) end private def respond_html(content, status: 200) [status, {'Content-Type' => 'text/html'}, [content]] end end