Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created February 28, 2024 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/5b50f0f8f18589ad378281ecae52d888 to your computer and use it in GitHub Desktop.
Save havenwood/5b50f0f8f18589ad378281ecae52d888 to your computer and use it in GitHub Desktop.
An example of a streaming Rack app with NoHeaders and NoBody middleware
# frozen_string_literal: true
##
# A Rack app that streams a simple HTML page.
module App
PRETEND_TO_WAIT_FOR_IO = proc do
sleep 2
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'
end
HEADERS = {'content-type' => 'text/html; charset=utf-8'}.freeze
BODY = proc do |stream|
stream << "<!DOCTYPE html>\n<html lang=\"en\">\n"
stream << "<head><meta charset=\"utf-8\"><title>Hello, World!</title></head>\n"
stream << "<body>\n<h1>Hello, World!</h1>\n"
stream << "<p>#{PRETEND_TO_WAIT_FOR_IO.call}</p>\n"
stream << "</body>\n</html>\n"
ensure
stream.close
end
def self.call(_env) = [200, HEADERS.dup, BODY]
end
##
# Rack middleware that strips headers from the response.
class NoHeaders
NO_HEADERS = {}.freeze
def initialize(app) = @app = app
def call(env)
status, _headers, body = @app.call(env)
[status, NO_HEADERS.dup, body]
end
end
##
# Rack middleware that strips the body from the response.
class NoBody
NO_BODY = ->(_stream) {}
def initialize(app) = @app = app
def call(env)
status, headers, _body = @app.call(env)
[status, headers, NO_BODY]
end
end
##
# A Rack app with optional NoHeaders and NoBody middleware.
app = Rack::Builder.app do
# use NoHeaders
# use NoBody
run App
end
run app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment