Skip to content

Instantly share code, notes, and snippets.

@jjn1056
Forked from kraih/streaming-psgi.pl
Last active October 22, 2015 02:32
Show Gist options
  • Save jjn1056/108ae8c26418cf224f7e to your computer and use it in GitHub Desktop.
Save jjn1056/108ae8c26418cf224f7e to your computer and use it in GitHub Desktop.
# 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