为 Rails 中的特定路由执行机架中间件 [英] Execute Rack Middleware for Specific Routes in Rails

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

问题描述

我正在集成一个 3rd 方 API,并且在一个步骤中他们将 JSON 数据发布到我们的服务器中.

I'm integrating a 3rd party API, and at one step they post JSON data into our server.

内容类型是application/json,但是payload实际上是gzip压缩的.由于内容类型,rails 在尝试解析数据时抛出 ActionDispatch::ParamsParser::ParseError 异常.

The content type is application/json, but the payload is actually gzipped. Due to the content type, rails is throwing an ActionDispatch::ParamsParser::ParseError exception when trying to parse the data.

我打算编写一个机架中间件来捕获异常并尝试解压缩有效负载,但我只想为该特定操作执行此操作,有没有办法仅针对特定路由执行中间件?

I plan to write a rack middleware to catch the exception and try and uncompress the payload, but I only want to do it for that particular action, is there a way to execute the middleware only for specific routes?

更新

我已经考虑过对路径进行模式匹配,但理想情况下,我想要一些更健壮的东西,以防将来路径发生变化.

I'd already thought about pattern matching the path, but ideally I'd like something that is a little more robust in case paths change in the future.

更新

下面马特的评论更好地解决了有关压缩的问题,并且路由在另一个问题中得到了回答,该问题现在被标记为重复.

The issue regarding compression is better approached by matt's comment below, and the routing is answered in another question that this is now marked a duplicate of.

推荐答案

您可以轻松地对路径进行正则表达式匹配,并且仅在路径匹配时才执行解压缩代码.在这种情况下,您不会跳过所有其他路由的中间件,但处理检查应该非常轻量级.将其放在 lib/middleware/custom_middleware.rb 中:

You can easily to do a regex match on the path, and only execute uncompress code when the path matches. In this case, you are not skipping the middleware for all other routes, but processing the check should be very lightweight. Place this in lib/middleware/custom_middleware.rb:

class CustomMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    @req = Rack::Request.new(env)

    if should_use_this?
      # Your custom code goes here.
    end
  end


  def should_use_this?
    @req.path =~ /^matchable_path/ # Replace "matchable_path" with the path in question.
  end

end

然后将以下内容放入您的 config/environments/production.rb

Then put the following in your config/environments/production.rb

config.middleware.use "CustomMiddleware"

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

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