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, headerstart) ⇒ 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, headerstart) # rubocop:disable ParameterLists
  @body           = body
  @socket         = socket
  @headers        = headers
  @request_header = [headerstart]

  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



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

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

#join_headersObject

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



44
45
46
47
48
# File 'lib/http/request/writer.rb', line 44

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



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/http/request/writer.rb', line 58

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



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

def send_request_header
  add_headers
  add_body_type_headers
  header = join_headers

  @socket << header
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