api.rb 1.19 KB
module Lxd::API
  def self.get host, certificate
    begin
      uri = URI.parse host.uri
    rescue
    end
    con = Net::HTTP.new uri.host, uri.port ? uri.port : 8443
    con.use_ssl = true
    con.cert = OpenSSL::X509::Certificate.new certificate.cert
    con.key = OpenSSL::PKey::RSA.new certificate.key
    con.verify_mode = OpenSSL::SSL::VERIFY_NONE

    resp = self.call con, Net::HTTP::Get.new('/')
    return Lxd::API::V1_0.new con if resp['metadata'].include? '/1.0'
    raise "unsupported api version"
  end

  def self.call con, req
    resp = con.request req
    raise "request failure: " + resp.code unless resp.code != 200
    JSON.parse resp.body
  end

  def initialize con
    @con = con
  end

  def call req
    handle_response(Lxd::API.call @con, req)
  end

  def get uri
    call Net::HTTP::Get.new uri
  end

  def put uri, data={}
    request = Net::HTTP::Put.new uri
    request.body = data.to_json
    call request
  end

  def post uri, data={}
    request = Net::HTTP::Post.new uri
    request.body = data.to_json
    call request
  end

  def delete uri, data={}
    request = Net::HTTP::Delete.new uri
    request.body = data.to_json
    call request
  end
end
# vim: set et ts=2 sw=2: