我正在制作一个简单的方法来检查网站是否已启动,这是我的Ping模型,其中包含一些我要检查的地址
require 'net/http'
def self.check
pings = Ping.all
pings.each do |p|
http = Net::HTTP.new(p.address,80)
response = http.request_get('/')
if response.message == ( 'OK' or 'Found')
puts 'up!!'
end
end
end
我只是检查响应消息是“OK”还是“Found”,但我或者语句只检查“OK”。
这也是检查的好方法吗?
答案 0 :(得分:1)
response.message == ( 'OK' or 'Found')
不会按照您的想法行事。
> ( 'OK' or 'Found')
=> "OK"
这就是为什么它只检查" OK"。恕我直言,你不应该检查消息,因为这可能会有所不同。检查响应代码中是否存在200或300范围内的任何内容。
只要您不检查很多网站,上述情况就可以了。如果你是,它可能会开始需要一段时间,因为它们是顺序的。
您可能还想添加超时,以便在尝试ping并在20秒内失败时,请考虑将该网站关闭。
此外,我知道有些网站会为无法识别的用户代理返回400错误。所以你通过浏览器看到的内容可能根本不是你的脚本。
答案 1 :(得分:0)
As pointed out by @PhilipHallstrom, your mongodb://127.0.0.1:3001/local
statement isn't doing what you think it's doing. (if
!= if a== (b or c)
... Also, there is the issue of case sensitive equality.
Try a Regexp with the case insensitive configuration (the if a == b || a == c
at the end):
i
... although...
I support @PhilipHallstrom's reservations about the code.
Numerical codes would probably be better and application responsiveness should be a factor in the design (I assume you have that one covered)...
I would probably go for:
response.message.match /^(ok|found)$/i