在控制器导轨中检查redirect_to之前的url状态代码 [英] Check on the status code of url before redirect_to in controller rails

查看:66
本文介绍了在控制器导轨中检查redirect_to之前的url状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 instances_controller 中有操作 check_status ,我想在redirect_to之前检查URL的状态码。

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

如果 status_code 是200 redirect_to,否则进入查看页面。

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

这是 check_status 操作的伪代码:

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

示例 get'/ about'=> 'instances#check_status',我想检查(web.com)是否获得 status = 200 访问(web.com)

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

推荐答案

您可以执行此操作-但要注意:

You can do this - but beware:


  1. 您的用户将必须等待您的响应检查完成才能重定向。如果您正在检查速度较慢的服务器,则可能最多需要30秒才能将它们发送到其他地方。

  2. 不能保证用户将获得与您检查时得到的结果相同的结果。

以下代码使用 Ruby的 Net :: HTTP 模块来执行该Web请求:

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

请确保您将完整的URL传递给此方法,并使用 http:// https:// 前缀完成,或这行不通。

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

如果您担心性能下降,可以将结果缓存一会儿,然后在返回之前检查结果。即,当您查找URL时,可以节省查找时间。检索到的状态码。然后,在下一次查找中,如果您在过去24小时内检查了该域,请立即返回重定向,而无需再次检查。

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.

这篇关于在控制器导轨中检查redirect_to之前的url状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆