Last active
May 25, 2016 05:48
-
-
Save aasmith/5ac7173558753be8125bf95705602385 to your computer and use it in GitHub Desktop.
Rails Streaming: chunked + gzip/deflate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Adapted from http://stackoverflow.com/questions/7986150/http-streaming-in-rails-not-working-when-using-rackdeflater | |
| # | |
| # * Place this file in config/initializers/streaming.rb. | |
| # * Place 'config.middleware.use Rack::Deflater' in application.rb. | |
| # * Ensure you have a controller action that uses 'render stream: true' | |
| # * This should work in rails 3.1+, 4.x, and 5.x. See the original class: | |
| # https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/streaming.rb | |
| module GzipStreaming | |
| def _process_options(options) | |
| stream = options.delete(:stream) | |
| super | |
| if stream && env["HTTP_VERSION"] != "HTTP/1.0" | |
| headers["Cache-Control"] ||= "no-cache" | |
| headers.delete('Content-Length') | |
| options[:stream] = stream | |
| end | |
| end | |
| def _render_template(options) | |
| if options.delete(:stream) | |
| view_renderer.render_body(view_context, options) | |
| else | |
| super | |
| end | |
| end | |
| end | |
| module ActionController | |
| class Base | |
| include GzipStreaming | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Example of a response that chunks with gzip. (In this example, the "I streamed" block appears after a two second sleep.) | |
| $ curl -4vvv --compressed localhost:3000/s | |
| * Trying 127.0.0.1... | |
| * Connected to localhost (127.0.0.1) port 3000 (#0) | |
| > GET /s HTTP/1.1 | |
| > Host: localhost:3000 | |
| > User-Agent: curl/7.43.0 | |
| > Accept: */* | |
| > Accept-Encoding: deflate, gzip | |
| > | |
| < HTTP/1.1 200 OK | |
| < Cache-Control: no-cache | |
| < Content-Type: text/html; charset=utf-8 | |
| < Vary: Accept-Encoding | |
| < Content-Encoding: deflate | |
| < X-UA-Compatible: IE=Edge | |
| < X-Request-Id: 4a675d5a4c34d5b8ac38a4097ce8ba04 | |
| < X-Runtime: 0.022524 | |
| < Transfer-Encoding: chunked | |
| < | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Streaming</title> | |
| </head> | |
| <body> | |
| This is the layout body... | |
| I streamed. | |
| </body> | |
| </html> | |
| * Connection #0 to host localhost left intact | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment