module RegistryApiClient::HTTP

Public Instance Methods

execute(method:, url:, headers: {}, user: nil, password: nil, block_response: nil, body: nil, query: nil) click to toggle source
# File lib/docker_cake/registry_api_client.rb, line 416
def execute(method:, url:, headers: {}, user: nil, password: nil, block_response: nil, body: nil, query: nil)
  if query
    uri = URI.parse(url)
    url += (uri.query ? "&" : "?") + URI.encode_www_form(query)
  end
  uri = URI.parse(url)
  response = nil

  Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http_klass = case method.to_sym
      when :get    then Net::HTTP::Get
      when :post   then Net::HTTP::Post
      when :put    then Net::HTTP::Put
      when :patch  then Net::HTTP::Patch
      when :head   then Net::HTTP::Head
      when :delete then Net::HTTP::Delete
      when :move   then Net::HTTP::Move
      when :copy   then Net::HTTP::Copy
      else Net::HTTP::Post
    end

    request = http_klass.new(uri)
    headers.each do |key, value|
      request[key.to_s] = value
    end

    if body
      request.body = body
    end

    if user != nil || password != nil
      request.basic_auth(user, password)
    end

    puts "HTTP req #{method} #{url} #{headers}" if ENV['DEBUG']

    http_resp = http.request(request)

    puts "-> HTTP status: #{http_resp.code} size: #{http_resp.body.size}" if ENV['DEBUG']

    response = Response.new(http_resp)

    if http_resp.code.to_s == "401"
      raise Unauthorized.new(http_resp.body, response)
    end

    if http_resp.code.to_s == "405"
      raise MethodNotAllowed.new(http_resp.body, response)
    end

    if http_resp.code.to_s == '404'
      raise NotFound.new(http_resp.body, response)
    end

    return response
  end
end