Rails 如何檢查 URL 是否存在?

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
624   0  
·
2018/08/10
·
2 mins read


檢查一個網址是不是存在,這是一個很常要用到功能,特別是如果你的網頁允許使用者輸入資料,常常,他所指定的網址久了會不見或是不動了,網路上有很多解法,但是我喜歡以下這種有 time out 的解法,這樣就可以避開有些很慢的網頁整個拖累了你自己網頁的回應,我覺得這樣對使用者的體驗很重要,還有,如果網頁回應太慢,就當他不存在吧⋯⋯ 當然,如果你一定要到這個網址,那就不能用 Time out 的方法的。

這個功能常用在 view,所以我們就寫一個 helper,不多說,放碼:

def redirect_to_ok_url(default = root_url)
  url_valid = false
if default.present?
uri=URI.parse(default.present)
req = Net::HTTP.new(uri.host, uri.port)
req.open_timeout = 2 # 等最多兩秒
req.read_timeout = 2 # 等最多兩秒
if uri.scheme == "https" then req.use_ssl=true end # 設定 https
begin
res = req.request_head uri.path
  url_valid = true
  rescue
  url_valid = false
end
# ^ end of begin
else
  url_valid = false
end
# ^ end of if default.present?

  if url_valid
redirect_to default and return
else
redirect_to root_url and return # 這就看你需要來設定了
end
end

 

如果你一定要到這個網址,在 stack overflow 上,這裡有人的建議是只用 status code 不等於 404 來判斷網址是不是存在,我覺得是個很好的參考,要不要用,就由您自己決定了。


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

Categories:
Tags:
Total: 346 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.