我在 rails 中使用 net/http 从 URL 中获取响应代码,代码如下;
require "net/http"
require "uri"
class Status
def initialize(url)
@url = url
end
def get_status
begin
response.code
rescue Exception => e
Rails.logger.info("Error #{e}")
end
end
def active?
["200","203","302","301"].include?(get_status) ? true : false
end
private
def lookup
URI.parse(@url)
end
def http
Net::HTTP.new(lookup.host, lookup.port)
end
def request
Net::HTTP::Get.new(lookup.request_uri)
end
def response
http.request(request)
end
end
虽然它正确地标记了失败,但它显示所有是否通过或失败的代码作为状态代码:200,我怎样才能获得正确的状态代码?
控制器:
class EnvironmentsController < ApplicationController
def status
app = App.find(params[:app_id])
environment = app.environments.find{|env| env.id.to_s == params[:id]}
render json: {up:environment.up?}
end
end
看法:
<%- App.all.each do |app| %>
<h3><%= app.name %></h3>
<ul class="app" data-app-id="<%= app.id %>">
<%- app.environments.each do |environment| %>
<li class="env" data-env-id="<%= environment.id %>">
<strong><%= environment.name %></strong>
<%= environment.url %><span class="status"> Loading. . . </span>
<!-- <i> Status Code: <% puts response.code %></i> </li> -->
<% end %>
</ul>