lib/toycol/proxy.rb in toycol-0.3.0 vs lib/toycol/proxy.rb in toycol-0.3.1
- old
+ new
@@ -1,9 +1,7 @@
# frozen_string_literal: true
-require "socket"
-
module Toycol
class Proxy
include Helper
def initialize(host, port)
@@ -11,19 +9,19 @@
@port = port
@request_method = nil
@path = nil
@query = nil
@input = nil
- @protocol = ::Toycol::Protocol
+ @protocol = Protocol
@proxy = TCPServer.new(@host, @port)
end
CHUNK_SIZE = 1024 * 16
def start
- puts <<~MESSAGE
- Toycol is running on #{@host}:#{@port}
+ logger <<~MESSAGE
+ Start proxy server on #{@protocol.protocol_name} protocol, listening on #{@host}:#{@port}
=> Use Ctrl-C to stop
MESSAGE
loop do
trap(:INT) { shutdown }
@@ -31,17 +29,17 @@
@client = @proxy.accept
while !@client.closed? && !@client.eof?
begin
request = @client.readpartial(CHUNK_SIZE)
- puts "[Toycol] Received message: #{request.inspect.chomp}"
+ logger "Received message: #{request.inspect.chomp}"
safe_execution! { @protocol.run!(request) }
assign_parsed_attributes!
http_request_message = build_http_request_message
- puts "[Toycol] Message has been translated to HTTP request message: #{http_request_message.inspect}"
+ logger "Message has been translated to HTTP request message: #{http_request_message.inspect}"
transfer_to_server(http_request_message)
rescue StandardError => e
puts "#{e.class} #{e.message} - closing socket."
e.backtrace.each { |l| puts "\t#{l}" }
@proxy.close
@@ -80,37 +78,37 @@
def request_header
"Content-Length: #{@input&.bytesize || 0}\r\n"
end
def transfer_to_server(request_message)
- UNIXSocket.open(Toycol::UNIX_SOCKET_PATH) do |server|
+ UNIXSocket.open(UNIX_SOCKET_PATH) do |server|
server.write request_message
server.close_write
- puts "[Toycol] Successed to Send HTTP request message to server"
+ logger "Successed to Send HTTP request message to server"
response_message = []
response_message << server.readpartial(CHUNK_SIZE) until server.eof?
response_message = response_message.join
- puts "[Toycol] Received response message from server: #{response_message.lines.first}"
+ logger "Received response message from server: #{response_message.lines.first}"
response_line = response_message.lines.first
status_number = response_line[9..11]
status_message = response_line[12..].strip
if (custom_message = @protocol.status_message(status_number.to_i)) != status_message
response_message = response_message.sub(status_message, custom_message)
- puts "[Toycol] Status message has been translated to custom status message: #{custom_message}"
+ logger "Status message has been translated to custom status message: #{custom_message}"
end
@client.write response_message
@client.close_write
- puts "[Toycol] Finished to response to client"
+ logger "Finished to response to client"
server.close
end
end
def shutdown
- puts "[Toycol] Catched SIGINT -> Stop to server"
+ logger "Caught SIGINT -> Stop to server"
exit
end
end
end