Created
March 15, 2020 13:53
-
-
Save xiaohui-zhangxh/e21d71d9f90a878ca5b7a5aeb5408077 to your computer and use it in GitHub Desktop.
通过 UCloud API 管理资源
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'json' | |
require 'net/http' | |
require 'digest' | |
class UcloudAPI | |
API_HOST = 'https://api.ucloud.cn' | |
def initialize(public_key, private_key) | |
@public_key = public_key | |
@private_key = private_key | |
end | |
def request_api(action, params) | |
data = process_params(params).merge('Action' => action, 'PublicKey' => public_key) | |
data['Signature'] = signature(data) | |
body = Net::HTTP.get(URI(API_HOST + '?' + URI.encode_www_form(data))) | |
JSON.parse(body) | |
end | |
private | |
attr_reader :public_key, :private_key | |
def process_params(params) | |
new_params = {} | |
params.each_pair do |key, value| | |
if value.is_a?(Array) | |
value.each_with_index do |val, idx| | |
new_params["#{key}.#{idx}"] = val | |
end | |
else | |
new_params[key] = value | |
end | |
end | |
new_params | |
end | |
def signature(params) | |
sha1 = Digest::SHA1.new | |
params.keys.sort_by(&:to_s).each do |key| | |
sha1 << key << params[key].to_s | |
end | |
sha1 << private_key | |
sha1.hexdigest | |
end | |
end | |
if $0 == __FILE__ | |
public_key, private_key = ARGV[0,2] | |
client = UcloudAPI.new(public_key, private_key) | |
pp client.request_api('DescribeEIP', 'Region' => 'cn-bj2', 'ProjectId' => 'org-hencnd') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment