9/22/2006

偵測HTTP 狀態程式

這裡有一段Check HTTP 狀態的程式
基本上是用 crontab 去跑就好
log function 大家就自由發揮吧,看你要寫到那邊都隨便你
值得注意的是 response 不能直接用 == 去判斷Net::HTTPSuccess或是其他的狀態
因為Net::HTTPSuccess是一種很像是 range 的 object
直接用 == 判斷會判斷不出來得
建議是用 case when 來判斷,他會使用 === 來判斷
但是如果你要用 if 來改寫的話 ,必須寫成 Net::HTTPSuccess === response
我覺得這樣比較不直覺 :p


require 'net/http'

url = 'http://www.example.com'

response = Net::HTTP.get_response(URI.parse(url))

begin
case response
when Net::HTTPSuccess
log 'OK'
when Net::HTTPNotFound
log '404 Error'
when Net::HTTPInternalServerError
log 'Internal Server Error'
when Net::HTTPUnauthorized
log 'Unauthorized'
when Net::HTTPClientError
log 'Client Error'
when Net::HTTPRedirection
log 'Redirect'
when Net::HTTPInformation
log 'Informantion'
when Net::HTTPServerError
log 'Server Error'
when Net::HTTPUnknownResponse
log 'Unknown Response'
end
rescue Timeout::Error
log 'System Timeout'
end

以下的 code 可以偵測這個網頁處於那種狀態
我特別將 404 error ,500 error 挑出來
因為他是最容易發現的錯誤,你可以根據這個錯誤去做判斷
基本上只要有 response ,不管是那門子的 HTTP error ,Ruby 是不會 raise error 的
你必須使用 response.error! 或是 response.value 去 raise error
這樣的特性也比較好 coding

但是最後,我們還是得去抓 Timeout::Error
為什麼?我們公司有一台 server ,跑 lighttpd
因為 lighttpd 會去 query application server 的 backend process
當backend process 掛掉的時候,他就不回應給 lighttpd
遇到這種情況 Lighttpd 就不回你錯誤訊息
這樣子,一定要抓 Timeout::Error 才能知道出了啥問題

參考自Introduction to Ruby Net::HTTP,寫的很好
HTTP Response 列表可以參考自 Ruby Manual

沒有留言: