-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmocurl.rb
executable file
·99 lines (83 loc) · 2.55 KB
/
mocurl.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby
# frozen_string_literal: true
require "optparse"
require "yaml"
require "json"
require_relative "lib/moco"
options = { method: "GET", data: {}, api_key: nil, no_format: false, verbose: false }
OptionParser.new do |opts|
opts.banner = "Usage: #{$PROGRAM_NAME} [options] url\n " \
"#{$PROGRAM_NAME} [options] subdomain path"
opts.on("-X", "--method METHOD", "Set HTTP method to use") do |method|
options[:method] = method.upcase
end
opts.on("-d", "--data DATA", "Data to send to server, JSON format") do |data|
options[:data] = JSON.parse(data)
end
opts.on("-a", "--api-key API_KEY", "Manually specify MOCO API key") do |key|
options[:api_key] = key
end
opts.on("-n", "--no-format", "Disable JSON pretty-printing") do
options[:no_format] = true
end
opts.on("-v", "--verbose", "Show additional request and response information") do
options[:verbose] = true
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
def extract_subdomain(url)
url.match(%r{https?://([^.]+)\.mocoapp\.com})[1]
end
# Ensure we have a URL
url = ARGV.shift
if url.nil?
warn "Error: URL is required"
exit 1
end
if ARGV.empty?
subdomain = extract_subdomain(url)
else
subdomain = url
path = ARGV.shift
url = "https://#{subdomain}.mocoapp.com/api/v1/#{path.gsub(%r{\A/}, "")}"
end
# Load default API key from config
config = YAML.load_file("config.yml")
options[:api_key] ||= config["instances"].fetch(subdomain, nil)&.fetch("api_key", nil)
warn "Error: No API key found for `#{subdomain}' and none given, continuing without" if options[:api_key].nil?
api = MOCO::API.new(subdomain, options[:api_key])
case options[:method]
when "GET"
result = api.get(url)
when "DELETE"
result = api.delete(url)
when "POST"
result = api.post(url, options[:data])
when "PUT"
result = api.put(url, options[:data])
when "PATCH"
result = api.patch(url, options[:data])
else
puts "Error: Invalid HTTP Method: #{options[:method]}"
exit 1
end
if options[:verbose]
puts "> #{options[:method]} #{result.env.url}"
puts(result.env.request_headers.map do |k, v|
"> #{k}: #{k == "Authorization" ? "#{v[0...16]}<REDACTED>#{v[-4..]}" : v}"
end)
puts ">"
puts result.env.request_body.split.map { |l| "> #{l}" }.join if result.env.request_body
puts "---"
puts "< #{result.status} #{result.reason_phrase}"
puts(result.headers.map { |k, v| "< #{k}: #{v}" })
puts ""
end
if options[:no_format]
puts result.body.to_json
else
puts JSON.pretty_generate(result.body)
end