Skip to content

Instantly share code, notes, and snippets.

@aoyama-val
Created April 24, 2018 05:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aoyama-val/502631dc6e20d7987b9fc7b8bd521767 to your computer and use it in GitHub Desktop.
Save aoyama-val/502631dc6e20d7987b9fc7b8bd521767 to your computer and use it in GitHub Desktop.
Build curl command lines with Ruby
require "uri"
require "open3"
class CurlBuilder
def build(base_url:, method: "GET", params: {}, headers: {}, body_filename: nil, verbose: true, silent: true, options: "")
url = base_url
url += "?" + URI.encode_www_form(params) unless params.empty?
cmd = "curl -X #{method} '#{url}'"
cmd += " -d '@#{body_filename}'" if body_filename
cmd += " " + headers.map {|k, v| "-H '#{k}: #{v}'"}.join(" ") + " " unless headers.empty?
cmd += " -v " if verbose
cmd += " -s " if silent
cmd += options
return cmd
end
def exec(*args, **kwargs)
cmd = build(*args, **kwargs)
o, e, s = Open3.capture3(cmd)
print "\e[0;34m"
puts cmd
print "\e[0m"
print "\e[0;33m"
puts e
print "\e[0m"
print "\e[0;32m"
puts o
print "\e[0m"
end
end
@aoyama-val
Copy link
Author

Usage

c = CurlBuilder.new
puts c.build(base_url: "http://httpbin.org/get", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader"})
# => curl -X GET 'http://httpbin.org/get?a=123&b=hoge' -H 'X-Hoge: myheader'  -v  -s 
puts c.build(base_url: "http://httpbin.org/post", method: "POST", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader", "Content-Type": "application/json"}, body_filename: "body.json")
# => curl -X POST 'http://httpbin.org/post?a=123&b=hoge' -d '@body.json' -H 'X-Hoge: myheader' -H 'Content-Type: application/json'  -v  -s 

CurlBuilder#exec builds a command line and executes it. The executed command line, stderr, and stdout are printed with different colors. Handy in development.

c.exec(base_url: "http://httpbin.org/post", method: "POST", params: {a: 123, b: "hoge"}, headers: {"X-Hoge": "myheader", "Content-Type": "application/json"}, body_filename: "body.json")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment