Class: ThreadedProxy::SocketResponder

Inherits:
Object
  • Object
show all
Defined in:
lib/threaded_proxy/socket_responder.rb

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ SocketResponder

Returns a new instance of SocketResponder.



3
4
5
# File 'lib/threaded_proxy/socket_responder.rb', line 3

def initialize(socket)
  @socket = socket
end

Instance Method Details

#closeObject



57
58
59
# File 'lib/threaded_proxy/socket_responder.rb', line 57

def close
  @socket.close unless @socket.closed?
end

#closed?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/threaded_proxy/socket_responder.rb', line 61

def closed?
  @socket.closed?
end

#redirect_to(url) ⇒ Object



49
50
51
# File 'lib/threaded_proxy/socket_responder.rb', line 49

def redirect_to(url)
  render(status: 302, headers: { 'Location' => url })
end

#render(options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/threaded_proxy/socket_responder.rb', line 7

def render(options = {})
  return false if @socket.closed?

  status  = options[:status] || 200
  headers = options[:headers] || {}
  body    = options[:body]
  json    = options[:json]
  text    = options[:text]

  if json
    body = json.to_json
    headers['Content-Type'] ||= 'application/json; charset=utf-8'
  elsif text
    body = text
    headers['Content-Type'] ||= 'text/plain; charset=utf-8'
  else
    body ||= ''
  end

  response = ActionDispatch::Response.new(status, headers, [])
  response.prepare!

  # Build the HTTP response
  response_str = "HTTP/1.1 #{response.status} #{response.message}\r\n"
  response.headers.each do |key, value|
    Array(value).each do |v|
      response_str += "#{key}: #{v}\r\n"
    end
  end
  response_str += "\r\n"

  write(response_str)

  if body.respond_to?(:read)
    IO.copy_stream(body, @socket)
  else
    write(body)
  end

  close
end

#write(data) ⇒ Object



53
54
55
# File 'lib/threaded_proxy/socket_responder.rb', line 53

def write(data)
  @socket.write(data) unless @socket.closed?
end