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".freeze
ZERO =

Chunked data termintaor.

"0".freeze
CHUNKED =

Chunked transfer encoding

"chunked".freeze
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



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

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



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

def add_body_type_headers
  if @body.is_a?(String) && !@headers[Headers::CONTENT_LENGTH]
    @request_header << "#{Headers::CONTENT_LENGTH}: #{@body.bytesize}"
  elsif @body.is_a?(Enumerable) && CHUNKED != @headers[Headers::TRANSFER_ENCODING]
    fail(RequestError, "invalid transfer encoding")
  end
end

#add_headersObject

Adds headers to the request header from the headers array



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

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

#connect_through_proxyObject

Send headers needed to connect through proxy



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

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



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

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



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/http/request/writer.rb', line 71

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

#send_request_headerObject



64
65
66
67
68
69
# File 'lib/http/request/writer.rb', line 64

def send_request_header
  add_headers
  add_body_type_headers

  @socket << join_headers
end

#streamObject

Stream the request to a socket



35
36
37
38
# File 'lib/http/request/writer.rb', line 35

def stream
  send_request_header
  send_request_body
end