在特定的 Rails 路由上触发 Rack 中间件 [英] Trigger Rack middleware on specific Rails routes

查看:66
本文介绍了在特定的 Rails 路由上触发 Rack 中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以只在特定的 Rails 路由上触发 Rack 中间件?

Is it possible to trigger Rack middleware only on specific Rails routes?

例如,假设我只想在 api 命名空间上运行速率限制器中间件.

For example, let's say I wanted to run a rate limiter middleware only on the api namespace.

namespace :api do
  resources :users
end

推荐答案

我在 Rack 上取得了不错的成功::Throttle 用于速率限制.子类化一个内置的油门类并重载 allowed? 方法.您的自定义逻辑可以检查正在访问哪个控制器并根据需要应用速率限制.

I've had good success with Rack::Throttle for rate limiting. Subclass one of the built-in throttle classes and overload the allowed? method. Your custom logic can check which controller is being accessed and apply the rate limit as needed.

class ApiThrottle < Rack::Throttle::Hourly
  ##
  # Returns `false` if the rate limit has been exceeded for the given
  # `request`, or `true` otherwise.
  #
  # Rate limits are only imposed on the "api" controller
  #
  # @param  [Rack::Request] request
  # @return [Boolean]
  def allowed?(request)
    path_info = (Rails.application.routes.recognize_path request.url rescue {}) || {} 

    # Check if this route should be rate-limited
    if path_info[:controller] == "api"
      super
    else
      # other routes are not throttled, so we allow them
      true
    end
  end
end

这篇关于在特定的 Rails 路由上触发 Rack 中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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