Check on the status code of url before redirect_to in controller rails

我只是一个虾纸丫 提交于 2019-12-06 07:17:58

You can do this - but beware:

  1. Your user will have to wait for your response check to complete before they get redirected. If you're checking a slow server, that could be up to 30 seconds before they get sent somewhere else.
  2. There's no guarantee that the user will get the same result you got when you checked.

Here's some code that uses Ruby's Net::HTTP module to perform that web request:

require 'net/http'

def check_status(url)
  uri = URI(url)
  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Head.new uri.request_uri
    response = http.request request

    if response == Net::HTTPSuccess
      redirect_to url and return
    end
  end
end

Make sure you're passing in full URLs to this method, complete with an http:// or https:// prefix, or this won't work.

If you were worried about that performance hit, you could cache the results for a short while and check those before returning. That is, when you look up a URL you can save the time of the lookup & the status code retrieved. Then, on the next lookup, if you've checked that domain in the past 24 hours, return the redirect immediately rather than checking it again.

In addition to Alex's answer, you can use curl tool instead of Net::HTTP module.

system('curl www.google.com') # => true

system('curl www.google_not_valid.com') # => false

For me just this one is working to check the response

The == one gets no match...

response.is_a? Net::HTTPSuccess
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!