Created
June 24, 2022 09:21
-
-
Save Antti/c9daa78df12dfdc65e43a16f45f52a15 to your computer and use it in GitHub Desktop.
This file contains 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
require 'brotli' | |
module FeedRs | |
class BrotliDecompressionMiddleware < Faraday::Middleware | |
ACCEPT_ENCODING = 'Accept-Encoding'.freeze | |
CONTENT_ENCODING = 'Content-Encoding'.freeze | |
CONTENT_LENGTH = 'Content-Length'.freeze | |
SUPPORTED_ENCODINGS = 'br'.freeze | |
def call(env) | |
env[:request_headers][ACCEPT_ENCODING] = SUPPORTED_ENCODINGS | |
@app.call(env).on_complete do |response_env| | |
if response_env[:body].empty? | |
reset_body(response_env, &method(:raw_body)) | |
else | |
case response_env[:response_headers][CONTENT_ENCODING] | |
when 'br' | |
reset_body(response_env, &method(:brotli_inflate)) | |
else | |
reset_body(response_env, &method(:raw_body)) | |
end | |
end | |
end | |
end | |
def reset_body(env) | |
env[:body] = yield(env[:body]) | |
env[:response_headers].delete(CONTENT_ENCODING) | |
env[:response_headers][CONTENT_LENGTH] = env[:body].length | |
end | |
def brotli_inflate(body) | |
Brotli.inflate(body) | |
end | |
def raw_body(body) | |
body | |
end | |
Faraday::Response.register_middleware(brotli: -> { BrotliDecompressionMiddleware }) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment