Last active
December 18, 2017 20:21
-
-
Save ncuesta/5abe0d2e77017b341b490e3b07e4b92f to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
# Implementación sencilla de un clon de cURL para utilizar en el examen. | |
# El script debe invocarse como un ejecutable (deberás darle permisos | |
# de ejecución con `chmod +x curl.rb`) y espera recibir los siguientes | |
# argumentos: | |
# - La URL a la cual realizar la petición | |
# - El método http a utilizar (opcional), que puede ser GET, POST o | |
# DELETE (si se omite se considera GET). | |
# - El cuerpo de la petición a realizar (opcional, sólo aplica en caso | |
# de peticiones POST). | |
# | |
# En todos los casos se muestran el HTTP status y cuerpo de la respuesta | |
# recibida. | |
# | |
# Ejemplos de uso: | |
# | |
# $ ./curl.rb http://localhost:4567/test | |
# # => Realiza una petición GET a http://localhost:4567/test | |
# | |
# $ ./curl.rb http://localhost:4567/test post 'un=campo&otro=valor' | |
# # => Realiza una petición POST a http://localhost:4567/test | |
# con un=campo&otro=valor como cuerpo de la petición | |
# | |
# $ ./curl.rb http://localhost:4567/test DELETE | |
# # => Realiza una petición DELETE a http://localhost:4567/test | |
require 'net/http' | |
require 'uri' | |
target = ARGV[0] | |
method = case ARGV[1] | |
when /POST/i | |
Net::HTTP::Post | |
when /DELETE/i | |
Net::HTTP::Delete | |
else | |
Net::HTTP::Get | |
end | |
body = ARGV[2] | |
uri = URI.parse(target) | |
http = Net::HTTP.new(uri.host, uri.port) | |
request = method.new(uri.request_uri) | |
request.body = body if body | |
response = http.request(request) | |
puts "Request:\n========" | |
puts " Method: #{request.method}" | |
puts " URL: #{uri}" | |
puts " Body: #{request.body || '(ninguno)'}" | |
puts "Response:\n=========" | |
puts " Status: #{response.code}" | |
puts " Body: #{response.body}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment