是否可以仅在特定的Rails路由上触发Rack中间件?
例如,假设我想仅在api命名空间上运行速率限制器中间件.
namespace :api do resources :users end
解决方法
我在
Rack::Throttle的速率限制方面取得了很大的成功.子类一个内置的油门类和重载允许的?方法.您的自定义逻辑可以检查正在访问的控制器,并根据需要应用速率限制.
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