# File lib/http/request/writer.rb, line 22 def initialize(socket, body, headers, headline) @body = body @socket = socket @headers = headers @request_header = [headline] validate_body_type! end
Adds the headers to the header array for the given request body we are working with
# File lib/http/request/writer.rb, line 53 def add_body_type_headers if @body.is_a?(String) && !@headers[Headers::CONTENT_LENGTH] @request_header << "#{Headers::CONTENT_LENGTH}: #{@body.bytesize}" elsif @body.nil? && !@headers[Headers::CONTENT_LENGTH] @request_header << "#{Headers::CONTENT_LENGTH}: 0" elsif @body.is_a?(Enumerable) && CHUNKED != @headers[Headers::TRANSFER_ENCODING] raise(RequestError, "invalid transfer encoding") end end
Adds headers to the request header from the headers array
# File lib/http/request/writer.rb, line 32 def add_headers @headers.each do |field, value| @request_header << "#{field}: #{value}" end end
Send headers needed to connect through proxy
# File lib/http/request/writer.rb, line 46 def connect_through_proxy add_headers write(join_headers) end
Joins the headers specified in the request into a correctly formatted http request header string
# File lib/http/request/writer.rb, line 65 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
# File lib/http/request/writer.rb, line 71 def send_request headers = join_headers # It's important to send the request in a single write call when # possible in order to play nicely with Nagle's algorithm. Making # two writes in a row triggers a pathological case where Nagle is # expecting a third write that never happens. case @body when NilClass write(headers) when String write(headers << @body) when Enumerable write(headers) @body.each do |chunk| write(chunk.bytesize.to_s(16) << CRLF << chunk << CRLF) end write(CHUNKED_END) else raise TypeError, "invalid body type: #{@body.class}" end end
Stream the request to a socket
# File lib/http/request/writer.rb, line 39 def stream add_headers add_body_type_headers send_request end
# File lib/http/request/writer.rb, line 105 def validate_body_type! return if VALID_BODY_TYPES.any? { |type| @body.is_a? type } raise RequestError, "body of wrong type: #{@body.class}" end
# File lib/http/request/writer.rb, line 97 def write(data) until data.empty? length = @socket.write(data) break unless data.bytesize > length data = data.byteslice(length..-1) end end