Class: RightSpeed::Handler::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/right_speed/handler.rb

Constant Summary collapse

READ_CHUNK_LENGTH =
1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handler, conn) ⇒ Session

Returns a new instance of Session.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/right_speed/handler.rb', line 136

def initialize(handler, conn)
  @logger = RightSpeed.logger
  @handler = handler
  @conn = conn
  @client = Client.new(conn)

  # https://github.com/tmm1/http_parser.rb
  @parser = Http::Parser.new(self, default_header_value_type: :mixed)
  @reading = true
  @method = nil
  @url = nil
  @headers = nil
  @body = String.new
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



134
135
136
# File 'lib/right_speed/handler.rb', line 134

def logger
  @logger
end

Instance Method Details

#on_body(chunk) ⇒ Object



167
168
169
# File 'lib/right_speed/handler.rb', line 167

def on_body(chunk)
  @body << chunk
end

#on_headers_complete(headers) ⇒ Object



161
162
163
164
165
# File 'lib/right_speed/handler.rb', line 161

def on_headers_complete(headers)
  @headers = headers
  @method = @parser.http_method
  @url = @parser.request_url
end

#on_message_completeObject



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/right_speed/handler.rb', line 171

def on_message_complete
  # @logger.debug {
  #   "complete to read the request, headers:#{@headers}, body:#{@body}"
  # }
  request = Request.new(
    client: @client, http_method: @method, http_version: @parser.http_version,
    request_url: @url, headers: @headers, body: @body
  )
  response = @handler.process(self, @client, request)
  send_response(response)
  @reading = false
end

#processObject



155
156
157
158
159
# File 'lib/right_speed/handler.rb', line 155

def process
  while @reading && !@conn.eof?
    @parser << @conn.readpartial(READ_CHUNK_LENGTH)
  end
end

#send_response(response) ⇒ Object



184
185
186
187
188
189
190
# File 'lib/right_speed/handler.rb', line 184

def send_response(response)
  @conn.write response.status
  @conn.write response.headers
  response.body.each do |part|
    @conn.write part
  end
end