Class: HTTP::RequestStream

Inherits:
Object
  • Object
show all
Defined in:
lib/http/request_stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(socket, body, headers, headerstart) ⇒ RequestStream

Returns a new instance of RequestStream.

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
# File 'lib/http/request_stream.rb', line 3

def initialize(socket, body, headers, headerstart)
  @body           = body
  raise ArgumentError, "body of wrong type" unless valid_body_type
  @socket         = socket
  @headers        = headers
  @request_header = [headerstart]
end

Instance Method Details

#add_body_type_headersObject

Adds the headers to the header array for the given request body we are working with



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/http/request_stream.rb', line 32

def add_body_type_headers
  if @body.is_a? String and not @headers['Content-Length']
    @request_header << "Content-Length: #{@body.length}"
  elsif @body.is_a? Enumerable
    if encoding = @headers['Transfer-Encoding'] and not encoding == "chunked"
      raise ArgumentError, "invalid transfer encoding"
    else
      @request_header << "Transfer-Encoding: chunked"
    end
  end
end

#add_headersObject

Adds headers to the request header from the headers array



18
19
20
21
22
# File 'lib/http/request_stream.rb', line 18

def add_headers
  @headers.each do |field, value|
    @request_header << "#{field}: #{value}"
  end
end

#join_headersObject

Joins the headers specified in the request into a correctly formatted http request header string



46
47
48
49
50
# File 'lib/http/request_stream.rb', line 46

def join_headers
  # join the headers array with crlfs, stick two on the end because
  # that ends the request header
  @request_header.join(CRLF) + (CRLF)*2
end

#send_request_bodyObject



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/http/request_stream.rb', line 60

def send_request_body
  if @body.is_a? String
    @socket << @body
  elsif @body.is_a? Enumerable
    @body.each do |chunk|
      @socket << chunk.bytesize.to_s(16) << CRLF
      @socket << chunk
    end

    @socket << "0" << CRLF * 2
  end
end

#send_request_headerObject



52
53
54
55
56
57
58
# File 'lib/http/request_stream.rb', line 52

def send_request_header
  self.add_headers
  self.add_body_type_headers
  header = self.join_headers

  @socket << header
end

#streamObject

Stream the request to a socket



25
26
27
28
# File 'lib/http/request_stream.rb', line 25

def stream
  self.send_request_header
  self.send_request_body
end

#valid_body_typeObject



11
12
13
14
15
# File 'lib/http/request_stream.rb', line 11

def valid_body_type
  valid_types= [String, NilClass, Enumerable]
  checks = valid_types.map {|type| @body.is_a? type}
  checks.any?
end