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"

Instance Method Summary collapse

Constructor Details

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

rubocop:disable ParameterLists



7
8
9
10
11
12
13
# File 'lib/http/request/writer.rb', line 7

def initialize(socket, body, headers, headerstart) # rubocop:disable ParameterLists
  @body           = body
  fail(RequestError, '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



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/http/request/writer.rb', line 36

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

#add_headersObject

Adds headers to the request header from the headers array



22
23
24
25
26
# File 'lib/http/request/writer.rb', line 22

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



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

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



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

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



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

def send_request_header
  add_headers
  add_body_type_headers
  header = join_headers

  @socket << header
end

#streamObject

Stream the request to a socket



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

def stream
  send_request_header
  send_request_body
end

#valid_body_typeObject



15
16
17
18
19
# File 'lib/http/request/writer.rb', line 15

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