问题
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