Created
August 10, 2020 16:11
-
-
Save TarasJan/6549ad18612896d69b7cbeaaa5525eaf to your computer and use it in GitHub Desktop.
Aftermath of our conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'socket' | |
require 'uri' | |
require 'cgi' | |
module Esnictoiat | |
class Router | |
def self.get(url_path, options) | |
@@routes ||= {} | |
@@routes[url_path] ||= {} | |
@@routes[url_path]['GET'] = options[:to] | |
end | |
def route(path, verb) | |
@@routes.dig(path, verb) | |
end | |
get '/hello', to: 'Hello#hello' | |
end | |
class Request | |
attr_reader :path, :verb, :params | |
def initialize(verb, path, params = nil) | |
@verb = verb | |
@path = path | |
@params = params | |
end | |
def run | |
router = Router.new | |
controller_name, action_name = router.route(path, verb)&.split('#') | |
unless controller_name && action_name | |
return "HTTP/1.1 404 Not Found" | |
end | |
controller_class = | |
Esnictoiat.const_get("#{controller_name.capitalize}Controller") | |
action_symbol = action_name.to_sym | |
controller_class.new(params).instance_eval(action_name) | |
end | |
end | |
class Params | |
attr_reader :raw_params, param_restrictions | |
def initialize(params) | |
@raw_params = params | |
end | |
def get(keyword) | |
pure_params = raw_params | |
param_restrictions[:required].each do |kw| | |
raise ArgumentError unless pure_params | |
end | |
pure_params.fetch(keyword.to_s, ['Fetch Error']).first | |
end | |
def permit(*param_names) | |
@param_restrictions[:permitted].concat([*param_names]) | |
end | |
def require(*param_names) | |
@param_restrictions[:required].concat([*param_names]) | |
end | |
end | |
class Controller | |
attr_reader :params, param_restrictions | |
def initialize(params) | |
@params = Params.new(params) | |
end | |
end | |
class HelloController < Esnictoiat::Controller | |
def hello | |
"HTTP/1.1 200 OK\n\nHello #{params.fetch('name', 'Stranger').first}!" | |
end | |
private | |
def hello_params | |
params.require(:params).permit(:name) | |
end | |
end | |
end | |
server = TCPServer.new 2020 | |
puts "CodequestServer 2020" | |
puts "=========================" | |
puts "I'm up and running" | |
loop do | |
client = server.accept | |
verb, url, _ = client.gets.split | |
url = URI(url) | |
query_params = CGI::parse(url.query) if url.query # TODO | |
response = Esnictoiat::Request.new(verb, url.path, query_params).run | |
client.puts response | |
client.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment