Execute Rack Middleware for Specific Routes in Rails [duplicate]

自闭症网瘾萝莉.ら 提交于 2020-01-11 12:05:20

问题


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

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?

Update

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.

Update

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.


回答1:


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

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

config.middleware.use "CustomMiddleware"


来源:https://stackoverflow.com/questions/34096098/execute-rack-middleware-for-specific-routes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!