Created
February 28, 2024 22:57
-
-
Save havenwood/5b50f0f8f18589ad378281ecae52d888 to your computer and use it in GitHub Desktop.
An example of a streaming Rack app with NoHeaders and NoBody middleware
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
# 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