Perl's PSGI/Plack and streaming response content

264 Views Asked by At

I'm exploring PSGI/Plack and how to do streaming/delayed responses. Already google'd around but find little to no examples of how to do it. Below are little bits and pieces I gathered from the PSGI::FAQ on metacpan. For example, if I want to stream response my long running simulateLongProcess() method below, how would I implement it using PSGI/Plack? Also, please share any links with examples related to this topic if possible. Thanks!

# Implementing delayed streaming response
use strict;
use warnings 'all';
no warnings 'uninitialized';
use Plack::Request;
sub say { print @_, "\n" }

my $app = sub {
  my $env = shift;
  unless ($env->{'psgi.streaming'}) {
    die "This application needs psgi.streaming support";
  }
  return sub {
    my $respond = shift;
    my $writer = $respond->([200, ['Content-Type', 'text/plain']]);
    wait_for_new_message(sub {
      my $message = shift;
      if ($message) {
        $writer->write($message->to_json);
      } else {
        $writer->close;
      }
    });
  };
};#end app

sub simulateLongProcess {#Params: none; #Return: void;
  for ( my $i=0; $i <= 5; $i++ ) {
    say $i;
    sleep( 3 );
  }#end for
}#end sub
0

There are 0 best solutions below