Skip to content

Instantly share code, notes, and snippets.

@JanDintel
Last active July 16, 2020 15:18
Show Gist options
  • Save JanDintel/d530433e347394a52bd33bb19f9d1864 to your computer and use it in GitHub Desktop.
Save JanDintel/d530433e347394a52bd33bb19f9d1864 to your computer and use it in GitHub Desktop.
Perform a HTTP GET request safely in Ruby, to answer https://twitter.com/mattiasgeniar/status/1283725453065367555
require 'net/http'
def ping(endpoint)
uri = URI.parse(endpoint)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
response.code == '200' #=> Returns either true or false
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError
false #=> Returns false when connection or request failed
end
ping('https://ohdear.app/ping/123')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment