-
-
Save jjn1056/108ae8c26418cf224f7e 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
# StreamingPSGI - Everything is streaming, no special cases | |
my $env = { | |
SERVER_NAME => 'localhost', | |
SERVER_PORT => 80, | |
SCRIPT_NAME => '', | |
REQUEST_METHOD => 'GET', | |
HTTP_CONTENT_LENGTH => 12, | |
version => 3, | |
url_scheme => 'http', | |
read => sub {...}, | |
status => sub {...}, | |
write => sub {...} | |
}; | |
# Streaming application | |
my $app = sub { | |
my $env = shift; | |
# Request body | |
my $input = ''; | |
$env->{read} = sub { | |
my $chunk = shift; | |
return $input .= $chunk if defined $chunk; | |
# Response | |
my $output = "echo: $input"; | |
$env->{status}->(200, 'OK', ['Content-Length' => length($output)]); | |
$env->{write}->($output); | |
}; | |
}; | |
# Streaming middleware | |
my $middleware = sub { | |
my ($env, $next) = @_; | |
# Response body | |
my $write = $env->{write}; | |
$env->{write} = sub { | |
my $chunk = shift; | |
say "OUTPUT CHUNK: $chunk"; | |
return $write->($chunk); | |
}; | |
# Forward to next middleware | |
$next->(); | |
# Request body | |
my $read = $env->{read}; | |
$env->{read} = sub { | |
my $chunk = shift; | |
say "INPUT CHUNK: $chunk"; | |
return $read->($chunk); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment