"Is my site down?" Howto
What's the best way to create a "Is my site down?" in Ruby? How should I do it to check it开发者_Go百科 using HTTP(s) and Ping?
Thanks.
Basically just use a http library to see if you can get (actually, HEADing would be better) the page they're pointing to. If you get a response then the server is up, otherwise (it doesn't respond or times out) it is down and you alert the user accordingly.
This isn't the cleanest way of doing it, but basically:
require 'net/http'
require 'uri'
def isUp( url )
uri = URI.parse( url )
begin
Timeout::timeout(5) {
Net::HTTP.start( uri.host, uri.port ) { |http|
http.head( uri.path )
}
}
rescue Timeout::Error
return false
end
return true
end
You can probably get it to not wait for the timeout, and/or increase the timeout to avoid the timeout to avoid false positive, but this is a simple example.
(cheat)
require 'uri'
require 'open-uri'
site = "http://stackoverflow.com/"
open("http://downforeveryoneorjustme.com/#{URI.parse(site).host}"){|f|f.read}["It's not just you!"]
精彩评论