Class: Excon::Connection
- Inherits:
-
Object
- Object
- Excon::Connection
- Defined in:
- lib/excon/connection.rb,
lib/excon/connection.rb
Instance Method Summary collapse
-
#initialize(url) ⇒ Connection
constructor
A new instance of Connection.
- #request(params) ⇒ Object
Constructor Details
#initialize(url) ⇒ Connection
Returns a new instance of Connection.
6 7 8 |
# File 'lib/excon/connection.rb', line 6 def initialize(url) @uri = URI.parse(url) end |
Instance Method Details
#request(params) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/excon/connection.rb', line 10 def request(params) begin params[:path] ||= '' unless params[:path][0..0] == '/' params[:path] = "/#{params[:path]}" end if params[:query] && !params[:query].empty? params[:path] << "?#{params[:query]}" end request = "#{params[:method]} #{params[:path]} HTTP/1.1\r\n" params[:headers] ||= {} params[:headers]['Host'] = params[:host] || @uri.host if params[:body] && !params[:headers]['Content-Length'] params[:headers]['Content-Length'] = params[:body].length end for key, value in params[:headers] request << "#{key}: #{value}\r\n" end request << "\r\n" connection.write(request) if params[:body] if params[:body].is_a?(String) connection.write(params[:body]) else while chunk = params[:body].read(CHUNK_SIZE) connection.write(chunk) end end end response = Excon::Response.new response.status = connection.readline[9..11].to_i while true data = connection.readline.chop! unless data.empty? header = data.split(': ') response.headers[header[0]] = header[1] else break end end unless params[:method] == 'HEAD' if !params[:block] || (params[:expects] && ![*params[:expects]].include?(response.status)) response.body = '' params[:block] = lambda { |chunk| response.body << chunk } end if response.headers['Content-Length'] remaining = response.headers['Content-Length'].to_i while remaining > 0 params[:block].call(connection.read([CHUNK_SIZE, remaining].min)) remaining -= CHUNK_SIZE end elsif response.headers['Transfer-Encoding'] == 'chunked' while true chunk_size = connection.readline.chomp!.to_i(16) chunk = connection.read(chunk_size + 2).chop! # 2 == "/r/n".length if chunk_size > 0 params[:block].call(chunk) else break end end elsif response.headers['Connection'] == 'close' params[:block].call(connection.read) @connection = nil end end rescue => connection_error @connection = nil raise(connection_error) end if params[:expects] && ![*params[:expects]].include?(response.status) raise(Excon::Errors.status_error(params, response)) else response end end |