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

旧街凉风 提交于 2019-12-10 10:34:46

问题


I have action check_status in instances_controller, and I want to check on status code of URL before redirect_to it.

if status_code is 200 redirect_to it, else go to view page.

This is the pseudo-code of check_status action:

def check_status
  if "http://www.web.com".status_code == 200
    redirect_to "http://www.web.com"
  else
    #DO Nothing, and go to its view
  end
end

For example get '/about' => 'instances#check_status', and i want to check if (web.com) get status=200 visit (web.com)


回答1:


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.




回答2:


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




回答3:


For me just this one is working to check the response

The == one gets no match...

response.is_a? Net::HTTPSuccess


来源:https://stackoverflow.com/questions/25220251/check-on-the-status-code-of-url-before-redirect-to-in-controller-rails

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