Class: Zold::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/http.rb

Overview

Http page

Constant Summary collapse

SCORE_HEADER =

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.

'X-Zold-Score'
VERSION_HEADER =

HTTP header we add, in order to inform the node about our version. This is done mostly in order to let the other node reboot itself, if the version is higher.

'X-Zold-Version'
NETWORK_HEADER =

HTTP header we add, in order to inform the node about our network. This is done in order to isolate test networks from production one.

'X-Zold-Network'
PROTOCOL_HEADER =

HTTP header we add, in order to inform the node about our protocol.

'X-Zold-Protocol'

Instance Method Summary collapse

Constructor Details

#initialize(uri:, score: Score::ZERO, network: 'test') ⇒ Http

Returns a new instance of Http.



102
103
104
105
106
# File 'lib/zold/http.rb', line 102

def initialize(uri:, score: Score::ZERO, network: 'test')
  @uri = uri.is_a?(URI) ? uri : URI(uri)
  @score = score
  @network = network
end

Instance Method Details

#get(timeout: READ_TIMEOUT) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/zold/http.rb', line 108

def get(timeout: READ_TIMEOUT)
  HttpResponse.new(
    Typhoeus::Request.get(
      @uri,
      accept_encoding: 'gzip',
      headers: headers,
      connecttimeout: CONNECT_TIMEOUT,
      timeout: timeout
    )
  )
rescue StandardError => e
  HttpError.new(e)
end

#get_file(file) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/zold/http.rb', line 122

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

#put(file) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/zold/http.rb', line 142

def put(file)
  HttpResponse.new(
    Typhoeus::Request.put(
      @uri,
      accept_encoding: 'gzip',
      body: IO.read(file),
      headers: headers.merge(
        'Content-Type': 'text/plain'
      ),
      connecttimeout: CONNECT_TIMEOUT,
      timeout: 2 + File.size(file) * 0.01 / 1024
    )
  )
rescue StandardError => e
  HttpError.new(e)
end