1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00
httparty/bin/httparty

98 lines
No EOL
2.4 KiB
Ruby
Executable file

#!/usr/bin/env ruby
require "optparse"
require "pp"
$:.unshift(File.join(File.dirname(__FILE__), "/../lib"))
require "httparty"
opts = {
:action => :get,
:headers => {},
:verbose => false
}
def die(msg)
STDERR.puts(msg)
exit 1
end
OptionParser.new do |o|
o.banner = "USAGE: #{$0} [options] [url]"
o.on("-f",
"--format [FORMAT]",
"Output format to use instead of pretty-print ruby: " +
"plain, json or xml") do |f|
opts[:output_format] = f.downcase.to_sym
end
o.on("-a",
"--action [ACTION]",
"HTTP action: get (default), post, put or delete") do |a|
opts[:action] = a.downcase.to_sym
end
o.on("-d",
"--data [BODY]",
"Data to put in request body (prefix with '@' for file)") do |d|
if d =~ /^@/
opts[:data] = open(d).read
else
opts[:data] = d
end
end
o.on("-H", "--header [NAME=VALUE]", "Additional HTTP headers in NAME=VALUE form") do |h|
die "Invalid header specification, should be Name:Value" unless h =~ /.+:.+/
name, value = h.split(':')
opts[:headers][name.strip] = value.strip
end
o.on("-v", "--verbose", "If set, print verbose output") do |v|
opts[:verbose] = true
end
o.on("-u", "--user [CREDS]", "Use basic authentication. Value should be user:password") do |u|
die "Invalid credentials format. Must be user:password" unless u =~ /.+:.+/
user, password = u.split(':')
opts[:basic_auth] = { :username => user, :password => password }
end
o.on("-h", "--help", "Show help documentation") do |h|
puts o
exit
end
end.parse!
puts "Querying #{ARGV.first} with options: #{opts.inspect}" if opts[:verbose]
if ARGV.empty?
STDERR.puts "You need to provide a URL"
STDERR.puts "USAGE: #{$0} [options] [url]"
end
if opts[:output_format].nil?
response = HTTParty.send(opts[:action], ARGV.first, opts)
puts "Status: #{response.code}"
pp response
else
print_format = opts[:output_format]
response = HTTParty.send(opts[:action], ARGV.first, opts)
puts "Status: #{response.code}"
case opts[:output_format]
when :json
begin
require 'rubygems'
require 'json'
puts JSON.pretty_generate(response.delegate)
rescue LoadError
puts YAML.dump(response.delegate)
end
when :xml
REXML::Document.new(response.body).write(STDOUT, 2)
puts
else
puts response
end
end