Created
July 18, 2014 16:46
-
-
Save mat/983b1f8ec900b61cc84e to your computer and use it in GitHub Desktop.
Typhoeus request to curl command string.
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
# | |
# Generate curl command from a Typhoeus request. | |
# | |
# Example: | |
# | |
# > request = Typhoeus::Request.post("http://example.com", {body: "fine stuff"}).request | |
# > TyphoeusToCurl.new.to_curl(request) | |
# | |
# => "curl 'http://example.com' -X POST -H \"User-Agent: Typhoeus" -d 'fine stuff' --compressed" | |
# | |
class TyphoeusToCurl | |
def to_curl(typhoeus_request) | |
url = "'#{typhoeus_request.url}'" | |
method = method(typhoeus_request) | |
headers = headers(typhoeus_request) | |
data = data(typhoeus_request) | |
["curl", url, method, headers, data, "--compressed"].compact.join(" ") | |
end | |
private | |
# -X PUT | |
def method(request) | |
if request.method.to_s == "get" | |
return nil | |
end | |
"-X #{request.method.to_s.upcase}" | |
end | |
# -H "Accept-Encoding: deflate, gzip" | |
def headers(request) | |
if request.headers.empty? | |
return nil | |
end | |
request.headers.map { |key, value| | |
%Q(-H "#{key}: #{value}") | |
} | |
end | |
# -d 'data....' | |
def data(request) | |
if request.body.nil? | |
return nil | |
end | |
"-d '#{request.body}'" | |
end | |
end |
silva96
commented
Jun 15, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment