Class: WEBrick::HTTPResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/webrick/httpresponse.rb

Overview

An HTTP response. This is filled in by the service or do_* methods of a WEBrick HTTP Servlet.

Defined Under Namespace

Classes: ChunkedWrapper, InvalidHeader

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ HTTPResponse

Creates a new HTTP response object. WEBrick::Config::HTTP is the default configuration.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/webrick/httpresponse.rb', line 99

def initialize(config)
  @config = config
  @buffer_size = config[:OutputBufferSize]
  @logger = config[:Logger]
  @header = Hash.new
  @status = HTTPStatus::RC_OK
  @reason_phrase = nil
  @http_version = HTTPVersion::convert(@config[:HTTPVersion])
  @body = ''
  @keep_alive = true
  @cookies = []
  @request_method = nil
  @request_uri = nil
  @request_http_version = @http_version  # temporary
  @chunked = false
  @filename = nil
  @sent_size = 0
  @bodytempfile = nil
end

Instance Attribute Details

#bodyObject

Body may be a String or IO-like object that responds to #read and #readpartial.



57
58
59
# File 'lib/webrick/httpresponse.rb', line 57

def body
  @body
end

#configObject (readonly)

Configuration for this response



88
89
90
# File 'lib/webrick/httpresponse.rb', line 88

def config
  @config
end

#cookiesObject (readonly)

Response cookies



46
47
48
# File 'lib/webrick/httpresponse.rb', line 46

def cookies
  @cookies
end

#filenameObject

Filename of the static file in this response. Only used by the FileHandler servlet.



78
79
80
# File 'lib/webrick/httpresponse.rb', line 78

def filename
  @filename
end

#headerObject (readonly)

Response header



41
42
43
# File 'lib/webrick/httpresponse.rb', line 41

def header
  @header
end

#http_versionObject (readonly)

HTTP Response version



31
32
33
# File 'lib/webrick/httpresponse.rb', line 31

def http_version
  @http_version
end

#keep_aliveObject

Is this a keep-alive response?



83
84
85
# File 'lib/webrick/httpresponse.rb', line 83

def keep_alive
  @keep_alive
end

#reason_phraseObject

Response reason phrase (“OK”)



51
52
53
# File 'lib/webrick/httpresponse.rb', line 51

def reason_phrase
  @reason_phrase
end

#request_http_versionObject

Request HTTP version for this response



72
73
74
# File 'lib/webrick/httpresponse.rb', line 72

def request_http_version
  @request_http_version
end

#request_methodObject

Request method for this response



62
63
64
# File 'lib/webrick/httpresponse.rb', line 62

def request_method
  @request_method
end

#request_uriObject

Request URI for this response



67
68
69
# File 'lib/webrick/httpresponse.rb', line 67

def request_uri
  @request_uri
end

#sent_sizeObject (readonly)

Bytes sent in this response



93
94
95
# File 'lib/webrick/httpresponse.rb', line 93

def sent_size
  @sent_size
end

#statusObject

Response status code (200)



36
37
38
# File 'lib/webrick/httpresponse.rb', line 36

def status
  @status
end

Instance Method Details

#[](field) ⇒ Object

Retrieves the response header field



137
138
139
# File 'lib/webrick/httpresponse.rb', line 137

def [](field)
  @header[field.downcase]
end

#[]=(field, value) ⇒ Object

Sets the response header field to value



144
145
146
# File 'lib/webrick/httpresponse.rb', line 144

def []=(field, value)
  @header[field.downcase] = value.to_s
end

#chunked=(val) ⇒ Object

Enables chunked transfer encoding.



195
196
197
# File 'lib/webrick/httpresponse.rb', line 195

def chunked=(val)
  @chunked = val ? true : false
end

#chunked?Boolean

Will this response body be returned using chunked transfer-encoding?

Returns:

  • (Boolean)


188
189
190
# File 'lib/webrick/httpresponse.rb', line 188

def chunked?
  @chunked
end

#content_lengthObject

The content-length header



151
152
153
154
155
# File 'lib/webrick/httpresponse.rb', line 151

def content_length
  if len = self['content-length']
    return Integer(len)
  end
end

#content_length=(len) ⇒ Object

Sets the content-length header to len



160
161
162
# File 'lib/webrick/httpresponse.rb', line 160

def content_length=(len)
  self['content-length'] = len.to_s
end

#content_typeObject

The content-type header



167
168
169
# File 'lib/webrick/httpresponse.rb', line 167

def content_type
  self['content-type']
end

#content_type=(type) ⇒ Object

Sets the content-type header to type



174
175
176
# File 'lib/webrick/httpresponse.rb', line 174

def content_type=(type)
  self['content-type'] = type
end

#eachObject

Iterates over each header in the response



181
182
183
# File 'lib/webrick/httpresponse.rb', line 181

def each
  @header.each{|field, value|  yield(field, value) }
end

#keep_alive?Boolean

Will this response’s connection be kept alive?

Returns:

  • (Boolean)


202
203
204
# File 'lib/webrick/httpresponse.rb', line 202

def keep_alive?
  @keep_alive
end

#make_body_tempfileObject

:nodoc:



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/webrick/httpresponse.rb', line 289

def make_body_tempfile # :nodoc:
  return if @bodytempfile
  bodytempfile = Tempfile.create("webrick")
  if @body.nil?
    # nothing
  elsif @body.respond_to? :readpartial
    IO.copy_stream(@body, bodytempfile)
    @body.close
  elsif @body.respond_to? :call
    @body.call(bodytempfile)
  else
    bodytempfile.write @body
  end
  bodytempfile.rewind
  @body = @bodytempfile = bodytempfile
  @header['content-length'] = bodytempfile.stat.size.to_s
end

#remove_body_tempfileObject

:nodoc:



307
308
309
310
311
312
313
# File 'lib/webrick/httpresponse.rb', line 307

def remove_body_tempfile # :nodoc:
  if @bodytempfile
    @bodytempfile.close
    File.unlink @bodytempfile.path
    @bodytempfile = nil
  end
end

#send_body(socket) ⇒ Object

Sends the body on socket



342
343
344
345
346
347
348
349
350
# File 'lib/webrick/httpresponse.rb', line 342

def send_body(socket) # :nodoc:
  if @body.respond_to? :readpartial then
    send_body_io(socket)
  elsif @body.respond_to?(:call) then
    send_body_proc(socket)
  else
    send_body_string(socket)
  end
end

#send_header(socket) ⇒ Object

Sends the headers on socket



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/webrick/httpresponse.rb', line 319

def send_header(socket) # :nodoc:
  if @http_version.major > 0
    data = status_line()
    @header.each{|key, value|
      tmp = key.gsub(/\bwww|^te$|\b\w/){ $&.upcase }
      data << "#{tmp}: #{check_header(value)}" << CRLF
    }
    @cookies.each{|cookie|
      data << "Set-Cookie: " << check_header(cookie.to_s) << CRLF
    }
    data << CRLF
    socket.write(data)
  end
rescue InvalidHeader => e
  @header.clear
  @cookies.clear
  set_error e
  retry
end

#send_response(socket) ⇒ Object

Sends the response on socket



209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/webrick/httpresponse.rb', line 209

def send_response(socket) # :nodoc:
  begin
    setup_header()
    send_header(socket)
    send_body(socket)
  rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ENOTCONN => ex
    @logger.debug(ex)
    @keep_alive = false
  rescue Exception => ex
    @logger.error(ex)
    @keep_alive = false
  end
end

#set_error(ex, backtrace = false) ⇒ Object

Creates an error page for exception ex with an optional backtrace



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/webrick/httpresponse.rb', line 369

def set_error(ex, backtrace=false)
  case ex
  when HTTPStatus::Status
    @keep_alive = false if HTTPStatus::error?(ex.code)
    self.status = ex.code
  else
    @keep_alive = false
    self.status = HTTPStatus::RC_INTERNAL_SERVER_ERROR
  end
  @header['content-type'] = "text/html; charset=ISO-8859-1"

  if respond_to?(:create_error_page)
    create_error_page()
    return
  end

  if @request_uri
    host, port = @request_uri.host, @request_uri.port
  else
    host, port = @config[:ServerName], @config[:Port]
  end

  error_body(backtrace, ex, host, port)
end

#set_redirect(status, url) ⇒ Object

Redirects to url with a WEBrick::HTTPStatus::Redirect status.

Example:

res.set_redirect WEBrick::HTTPStatus::TemporaryRedirect


359
360
361
362
363
364
# File 'lib/webrick/httpresponse.rb', line 359

def set_redirect(status, url)
  url = URI(url).to_s
  @body = "<HTML><A HREF=\"#{url}\">#{url}</A>.</HTML>\n"
  @header['location'] = url
  raise status
end

#setup_headerObject

Sets up the headers for sending



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/webrick/httpresponse.rb', line 226

def setup_header() # :nodoc:
  @reason_phrase    ||= HTTPStatus::reason_phrase(@status)
  @header['server'] ||= @config[:ServerSoftware]
  @header['date']   ||= Time.now.httpdate

  # HTTP/0.9 features
  if @request_http_version < "1.0"
    @http_version = HTTPVersion.new("0.9")
    @keep_alive = false
  end

  # HTTP/1.0 features
  if @request_http_version < "1.1"
    if chunked?
      @chunked = false
      ver = @request_http_version.to_s
      msg = "chunked is set for an HTTP/#{ver} request. (ignored)"
      @logger.warn(msg)
    end
  end

  # Determine the message length (RFC2616 -- 4.4 Message Length)
  if @status == 304 || @status == 204 || HTTPStatus::info?(@status)
    @header.delete('content-length')
    @body = ""
  elsif chunked?
    @header["transfer-encoding"] = "chunked"
    @header.delete('content-length')
  elsif %r{^multipart/byteranges} =~ @header['content-type']
    @header.delete('content-length')
  elsif @header['content-length'].nil?
    if @body.respond_to? :readpartial
    elsif @body.respond_to? :call
      make_body_tempfile
    else
      @header['content-length'] = (@body ? @body.bytesize : 0).to_s
    end
  end

  # Keep-Alive connection.
  if @header['connection'] == "close"
     @keep_alive = false
  elsif keep_alive?
    if chunked? || @header['content-length'] || @status == 304 || @status == 204 || HTTPStatus.info?(@status)
      @header['connection'] = "Keep-Alive"
    else
      msg = "Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true"
      @logger.warn(msg)
      @header['connection'] = "close"
      @keep_alive = false
    end
  else
    @header['connection'] = "close"
  end

  # Location is a single absoluteURI.
  if location = @header['location']
    if @request_uri
      @header['location'] = @request_uri.merge(location).to_s
    end
  end
end

#status_lineObject

The response’s HTTP status line



122
123
124
# File 'lib/webrick/httpresponse.rb', line 122

def status_line
  "HTTP/#@http_version #@status #@reason_phrase".rstrip << CRLF
end