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.

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.



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/webrick/httpresponse.rb', line 96

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
end

Instance Attribute Details

#bodyObject

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



54
55
56
# File 'lib/webrick/httpresponse.rb', line 54

def body
  @body
end

#configObject (readonly)

Configuration for this response



85
86
87
# File 'lib/webrick/httpresponse.rb', line 85

def config
  @config
end

#cookiesObject (readonly)

Response cookies



43
44
45
# File 'lib/webrick/httpresponse.rb', line 43

def cookies
  @cookies
end

#filenameObject

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



75
76
77
# File 'lib/webrick/httpresponse.rb', line 75

def filename
  @filename
end

#headerObject (readonly)

Response header



38
39
40
# File 'lib/webrick/httpresponse.rb', line 38

def header
  @header
end

#http_versionObject (readonly)

HTTP Response version



28
29
30
# File 'lib/webrick/httpresponse.rb', line 28

def http_version
  @http_version
end

#keep_aliveObject

Is this a keep-alive response?



80
81
82
# File 'lib/webrick/httpresponse.rb', line 80

def keep_alive
  @keep_alive
end

#reason_phraseObject

Response reason phrase (“OK”)



48
49
50
# File 'lib/webrick/httpresponse.rb', line 48

def reason_phrase
  @reason_phrase
end

#request_http_versionObject

Request HTTP version for this response



69
70
71
# File 'lib/webrick/httpresponse.rb', line 69

def request_http_version
  @request_http_version
end

#request_methodObject

Request method for this response



59
60
61
# File 'lib/webrick/httpresponse.rb', line 59

def request_method
  @request_method
end

#request_uriObject

Request URI for this response



64
65
66
# File 'lib/webrick/httpresponse.rb', line 64

def request_uri
  @request_uri
end

#sent_sizeObject (readonly)

Bytes sent in this response



90
91
92
# File 'lib/webrick/httpresponse.rb', line 90

def sent_size
  @sent_size
end

#statusObject

Response status code (200)



33
34
35
# File 'lib/webrick/httpresponse.rb', line 33

def status
  @status
end

Instance Method Details

#[](field) ⇒ Object

Retrieves the response header field



133
134
135
# File 'lib/webrick/httpresponse.rb', line 133

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

#[]=(field, value) ⇒ Object

Sets the response header field to value



140
141
142
# File 'lib/webrick/httpresponse.rb', line 140

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

#chunked=(val) ⇒ Object

Enables chunked transfer encoding.



191
192
193
# File 'lib/webrick/httpresponse.rb', line 191

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

#chunked?Boolean

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

Returns:

  • (Boolean)


184
185
186
# File 'lib/webrick/httpresponse.rb', line 184

def chunked?
  @chunked
end

#content_lengthObject

The content-length header



147
148
149
150
151
# File 'lib/webrick/httpresponse.rb', line 147

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

#content_length=(len) ⇒ Object

Sets the content-length header to len



156
157
158
# File 'lib/webrick/httpresponse.rb', line 156

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

#content_typeObject

The content-type header



163
164
165
# File 'lib/webrick/httpresponse.rb', line 163

def content_type
  self['content-type']
end

#content_type=(type) ⇒ Object

Sets the content-type header to type



170
171
172
# File 'lib/webrick/httpresponse.rb', line 170

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

#eachObject

Iterates over each header in the response



177
178
179
# File 'lib/webrick/httpresponse.rb', line 177

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

#keep_alive?Boolean

Will this response’s connection be kept alive?

Returns:

  • (Boolean)


198
199
200
# File 'lib/webrick/httpresponse.rb', line 198

def keep_alive?
  @keep_alive
end

#send_body(socket) ⇒ Object

Sends the body on socket



303
304
305
306
307
308
309
# File 'lib/webrick/httpresponse.rb', line 303

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

#send_header(socket) ⇒ Object

Sends the headers on socket



285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/webrick/httpresponse.rb', line 285

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}: #{value}" << CRLF
    }
    @cookies.each{|cookie|
      data << "Set-Cookie: " << cookie.to_s << CRLF
    }
    data << CRLF
    _write_data(socket, data)
  end
end

#send_response(socket) ⇒ Object

Sends the response on socket



205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/webrick/httpresponse.rb', line 205

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



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/webrick/httpresponse.rb', line 333

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

  @body = ''
  @body << <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
  <HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
  <BODY>
<H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
#{HTMLUtils::escape(ex.message)}
<HR>
  _end_of_html_

  if backtrace && $DEBUG
    @body << "backtrace of `#{HTMLUtils::escape(ex.class.to_s)}' "
    @body << "#{HTMLUtils::escape(ex.message)}"
    @body << "<PRE>"
    ex.backtrace.each{|line| @body << "\t#{line}\n"}
    @body << "</PRE><HR>"
  end

  @body << <<-_end_of_html_
<ADDRESS>
 #{HTMLUtils::escape(@config[:ServerSoftware])} at
 #{host}:#{port}
</ADDRESS>
  </BODY>
</HTML>
  _end_of_html_
end

#set_redirect(status, url) ⇒ Object

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

Example:

res.set_redirect WEBrick::HTTPStatus::TemporaryRedirect


324
325
326
327
328
# File 'lib/webrick/httpresponse.rb', line 324

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

#setup_headerObject

Sets up the headers for sending



222
223
224
225
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
# File 'lib/webrick/httpresponse.rb', line 222

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?
    unless @body.is_a?(IO)
      @header['content-length'] = @body ? @body.bytesize : 0
    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)
    end
  end
end

#status_lineObject

The response’s HTTP status line



118
119
120
# File 'lib/webrick/httpresponse.rb', line 118

def status_line
  "HTTP/#@http_version #@status #@reason_phrase #{CRLF}"
end

#to_sObject

:nodoc:



311
312
313
314
315
# File 'lib/webrick/httpresponse.rb', line 311

def to_s # :nodoc:
  ret = ""
  send_response(ret)
  ret
end