Class: HTTP::Request::Writer

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

Constant Summary collapse

CRLF =

CRLF is the universal HTTP delimiter

"\r\n"
VALID_BODY_TYPES =

Types valid to be used as body source

[String, NilClass, Enumerable]

Instance Method Summary collapse

Constructor Details

#initialize(socket, body, headers, headline) ⇒ Writer

rubocop:disable ParameterLists



10
11
12
13
14
15
16
17
# File 'lib/http/request/writer.rb', line 10

def initialize(socket, body, headers, headline) # rubocop:disable ParameterLists
  @body           = body
  @socket         = socket
  @headers        = headers
  @request_header = [headline]

  validate_body_type!
end

Instance Method Details

#add_body_type_headersObject

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



40
41
42
43
44
45
46
# File 'lib/http/request/writer.rb', line 40

def add_body_type_headers
  if @body.is_a?(String) && !@headers["Content-Length"]
    @request_header << "Content-Length: #{@body.bytesize}"
  elsif @body.is_a?(Enumerable) && "chunked" != @headers["Transfer-Encoding"]
    fail(RequestError, "invalid transfer encoding")
  end
end

#add_headersObject

Adds headers to the request header from the headers array



20
21
22
23
24
# File 'lib/http/request/writer.rb', line 20

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

#connect_through_proxyObject

Send headers needed to connect through proxy



33
34
35
36
# File 'lib/http/request/writer.rb', line 33

def connect_through_proxy
  add_headers
  @socket << join_headers
end

#join_headersObject

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



50
51
52
53
54
# File 'lib/http/request/writer.rb', line 50

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



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/http/request/writer.rb', line 63

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 << CRLF
    end

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

#send_request_headerObject



56
57
58
59
60
61
# File 'lib/http/request/writer.rb', line 56

def send_request_header
  add_headers
  add_body_type_headers

  @socket << join_headers
end

#streamObject

Stream the request to a socket



27
28
29
30
# File 'lib/http/request/writer.rb', line 27

def stream
  send_request_header
  send_request_body
end