Skip to content

Instantly share code, notes, and snippets.

@vishalkanaujia
Created August 12, 2019 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishalkanaujia/5c18933659ab98caaf680783f329d191 to your computer and use it in GitHub Desktop.
Save vishalkanaujia/5c18933659ab98caaf680783f329d191 to your computer and use it in GitHub Desktop.
require 'uri'
require 'net/http'
def get_server_connection(arg1, arg2)
http = nil
retries = 0
uri = URI("http://localhost:8089/")
begin
unless http
puts "Opening TCP connection..."
http = Net::HTTP.start(uri.host, uri.port, read_timeout: 5)
end
puts "Executing HTTP request..."
res = http.request_get(uri.path)
puts res.code, res.body
return res
rescue Errno::ECONNREFUSED, Net::ReadTimeout => e
# timeout would throw ReadTimeout exception
if (retries+=1) <= 3
puts "Timeout (#{e}), retrying in 1 second..."
sleep(retries) # Sleep more with each failure
retry # re-run the code!!
else
raise # All retries failed, raise the `last` seen exception
end
ensure
if http
puts "Closing the TCP connection..."
http.finish
end
end
end
def handle_backend_response(arg1, arg2)
res = get_server_connection(arg1, arg2)
unless res.nil? # did we get a response?
puts res.code, res.body
if res.code == "200"
return get_body_from_response(res.body)
end
if res.code == "404"
# handle 404 as you wish
return nil
else
puts "service unavailable"
return nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment