Class: Barrister::HttpTransport

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

Overview

Default HTTP transport implementation. This is a simple implementation that doesn’t support many options. We may extend this class in the future, but you can always write your own transport class based on this one.

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ HttpTransport

Takes the URL to the server endpoint and parses it



379
380
381
382
# File 'lib/barrister.rb', line 379

def initialize(url)
  @url = url
  @uri = URI.parse(url)
end

Instance Method Details

#request(req) ⇒ Object

‘request` is the only required method on a transport class.

‘req` is a JSON-RPC request with `id`, `method`, and optionally `params` slots.

The transport is very simple, and does the following:

  • Serialize ‘req` to JSON. Make sure to use `:ascii_only=true`

  • POST the JSON string to the endpoint, setting the MIME type correctly

  • Deserialize the JSON response string

  • Return the deserialized hash



395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/barrister.rb', line 395

def request(req)
  json_str = JSON::generate(req, { :ascii_only=>true })
  http    = Net::HTTP.new(@uri.host, @uri.port)
  request = Net::HTTP::Post.new(@uri.request_uri)
  request.body = json_str
  request["Content-Type"] = "application/json"
  response = http.request(request)
  if response.code != "200"
    raise RpcException.new(-32000, "Non-200 response #{response.code} from #{@url}")
  else
    return JSON::parse(response.body)
  end
end