Ruby on Rails API添加/status路由返回204状态码方法咨询
实现GET /status返回204状态码的简便方法
方法一:路由直接处理(最简便)
不需要创建控制器或模型,直接在路由定义里返回响应。打开config/routes.rb,添加以下任意一种写法即可:
# 原生Rack风格写法 get '/status', to: proc { [204, {}, []] } # 更贴合Rails习惯的写法 get '/status', to: ->(_) { head :no_content }
方法二:极简控制器(适合后续扩展)
如果后续可能需要在/status接口里添加更多检查逻辑(比如数据库连接、缓存状态等),可以创建一个无模型的极简控制器:
- 创建
app/controllers/status_controller.rb:
class StatusController < ApplicationController # 如果项目有全局身份验证拦截,需要跳过该接口的验证 skip_before_action :authenticate_user!, raise: false def index head :no_content end end
- 在
config/routes.rb中绑定路由:
get '/status', to: 'status#index'
验证方式
启动本地服务器后,用curl命令测试:
curl -I http://localhost:3000/status
响应头中会显示HTTP/1.1 204 No Content,说明配置生效。
内容的提问来源于stack exchange,提问作者inarrgd
相关产品推荐
相关产品推荐

