开发者

Rails 3 - Change HTTP Status to 200 and add status to response body

开发者 https://www.devze.com 2023-03-18 02:36 出处:网络
I need to catch the HTTP response just as it\'s leaving rails and rewri开发者_C百科te as follows:

I need to catch the HTTP response just as it's leaving rails and rewri开发者_C百科te as follows:

  1. Create a root status node with the status code in it, then
  2. Rewrite the header status to 200

Eg. For all responses, put their status as a root node and then rewrite their header:

HTTP/1.1 404 Not Found
Content-Type:text/html

This page was not found

Into this:

HTTP/1.1 200 OK
Content-Type: text/html

<status='404'>
This page was not found
</status>

Background: Using Rails 3 with a Flash client.

Anything other than HTTP 200 cannot be guaranteed to pass through to the client due to limitations of browsers. Some allow 201 through, but not all. Also, any headers will be stripped off most of the time, with only the body getting through.


I would use a Rack-Middleware since its really easy to process the header and rewrite the body. Put this into app/middleware/flashfix.rb

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

      def call(env)
        status, headers, response = @app.call(env)
        if status == 404 
          [200, headers, "<status='404'>" + response.body + "</status>"]
        else
          [status, headers, response]      
        end
      end
    end

This just checks if Rails returns a response with the status code "404" and then rewrites the the response accordingly. Then inside an intializer:

     # Loops through all middlewares and requires them
     Dir[File.join(Rails.root,"app/middleware/*.rb")].each do |middleware|
       require middleware
     end

With the middleware in place all you need to do is tell Rails to use it

    class Application < Rails::Application
      config.middleware.use "FlashFix"          
    end 

If you are unfamiliar with Rack I recommend http://guides.rubyonrails.org/rails_on_rack.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号