lib/zold/http.rb in zold-0.20.4 vs lib/zold/http.rb in zold-0.21.0

- old
+ new

@@ -30,10 +30,48 @@ # HTTP page. # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2018 Yegor Bugayenko # License:: MIT module Zold + # Some clients waits for status method in response + class HttpResponse < SimpleDelegator + def status + code.zero? ? 599 : code + end + + def status_line + status_message || '' + end + + def to_s + "#{status}: #{status_line}\n#{body}" + end + end + + # The error, if connection fails + class HttpError < HttpResponse + def initialize(ex) + @ex = ex + end + + def body + Backtrace.new(@ex).to_s + end + + def status + 599 + end + + def status_line + @ex.message || '' + end + + def headers + {} + end + end + # Http page class Http # HTTP header we add to each HTTP request, in order to inform # the other node about the score. If the score is big enough, # the remote node will add us to its list of remote nodes. @@ -66,76 +104,60 @@ @score = score @network = network end def get(timeout: READ_TIMEOUT) - Response.new( + HttpResponse.new( Typhoeus::Request.get( @uri, accept_encoding: 'gzip', headers: headers, connecttimeout: CONNECT_TIMEOUT, timeout: timeout ) ) rescue StandardError => e - Error.new(e) + HttpError.new(e) end - def put(body, timeout: READ_TIMEOUT) - Response.new( + def get_file(file) + File.open(file, 'w') do |f| + request = Typhoeus::Request.new( + @uri, + accept_encoding: 'gzip', + headers: headers, + connecttimeout: CONNECT_TIMEOUT + ) + request.on_body do |chunk| + f.write(chunk) + end + request.run + response = new HttpResponse(request) + raise "Invalid response code #{response.status}" unless response.status == 200 + response + end + rescue StandardError => e + HttpError.new(e) + end + + def put(file) + HttpResponse.new( Typhoeus::Request.put( @uri, accept_encoding: 'gzip', - body: body, - headers: headers.merge('Content-Type': 'text/plain'), + body: IO.read(file), + headers: headers.merge( + 'Content-Type': 'text/plain' + ), connecttimeout: CONNECT_TIMEOUT, - timeout: timeout + timeout: 2 + File.size(file) * 0.01 / 1024 ) ) rescue StandardError => e - Error.new(e) + HttpError.new(e) end private - - # Some clients waits for status method in response - class Response < SimpleDelegator - def status - code.zero? ? 599 : code - end - - def status_line - status_message || '' - end - - def to_s - "#{status}: #{status_line}\n#{body}" - end - end - - # The error, if connection fails - class Error < Response - def initialize(ex) - @ex = ex - end - - def body - Backtrace.new(@ex).to_s - end - - def status - 599 - end - - def status_line - @ex.message || '' - end - - def headers - {} - end - end def headers headers = { 'User-Agent': "Zold #{VERSION}", 'Connection': 'close',