class Sibit::Json

JSON processing.

Public Class Methods

new(log: Sibit::Log.new, http: Sibit::Http.new) click to toggle source

Constructor.

# File lib/sibit/json.rb, line 43
def initialize(log: Sibit::Log.new, http: Sibit::Http.new)
  @http = http
  @log = log
end

Public Instance Methods

get(address, headers: {}, accept: [200]) click to toggle source

Send GET request to the HTTP and return JSON response. This method will also log the process and will validate the response for correctness.

# File lib/sibit/json.rb, line 51
def get(address, headers: {}, accept: [200])
  start = Time.now
  uri = URI(address.to_s)
  res = @http.client(uri).get(
    "#{uri.path.empty? ? '/' : uri.path}#{uri.query ? "?#{uri.query}" : ''}",
    {
      'Accept' => 'application/json',
      'User-Agent' => user_agent,
      'Accept-Charset' => 'UTF-8',
      'Accept-Encoding' => ''
    }.merge(headers)
  )
  unless accept.include?(res.code.to_i)
    raise Sibit::Error, "Failed to retrieve #{uri} (#{res.code}): #{res.body}"
  end
  @log.info("GET #{uri}: #{res.code}/#{length(res.body.length)} in #{age(start)}")
  JSON.parse(res.body)
rescue JSON::ParserError => e
  raise Sibit::Error, "Can't parse JSON: #{e.message}"
end
post(address, body, headers: {}) click to toggle source
# File lib/sibit/json.rb, line 72
def post(address, body, headers: {})
  start = Time.now
  uri = URI(address.to_s)
  res = @http.client(uri).post(
    "#{uri.path}?#{uri.query}",
    "tx=#{CGI.escape(body)}",
    {
      'Accept' => 'text/plain',
      'User-Agent' => user_agent,
      'Accept-Charset' => 'UTF-8',
      'Accept-Encoding' => '',
      'Content-Type' => 'application/x-www-form-urlencoded'
    }.merge(headers)
  )
  unless res.code == '200'
    raise Sibit::Error, "Failed to post tx to #{uri}: #{res.code}\n#{res.body}"
  end
  @log.info("POST #{uri}: #{res.code} in #{age(start)}")
end

Private Instance Methods

age(start) click to toggle source
# File lib/sibit/json.rb, line 94
def age(start)
  "#{((Time.now - start) * 1000).round}ms"
end
length(bytes) click to toggle source
# File lib/sibit/json.rb, line 98
def length(bytes)
  if bytes > 1024 * 1024
    "#{bytes / (1024 * 1024)}mb"
  elsif bytes > 1024
    "#{bytes / 1024}kb"
  else
    "#{bytes}b"
  end
end
user_agent() click to toggle source
# File lib/sibit/json.rb, line 108
def user_agent
  "Anonymous/#{Sibit::VERSION}"
end