Amon2
view release on metacpan or search on metacpan
lib/Amon2/Plugin/Web/Streaming.pm view on Meta::CPAN
package Amon2::Plugin::Web::Streaming;
use strict;
use warnings;
use utf8;
use Amon2::Util;
use Amon2::Web::Response::Callback;
sub init {
my ($class, $c, $conf) = @_;
Amon2::Util::add_method(ref $c || $c, 'streaming', \&_streaming);
Amon2::Util::add_method(ref $c || $c, 'streaming_json', \&_streaming_json);
}
sub _streaming {
my ($self, $code) = @_;
return Amon2::Web::Response::Callback->new(
code => sub {
$code->(@_);
}
);
}
sub _streaming_json {
my ($self, $code) = @_;
return Amon2::Web::Response::Callback->new(
code => sub {
my $respond = shift;
my $writer = $respond->([200, ['Content-Type' => 'application/json;charset=utf-8']]);
my $longpoll_ctx = Amon2::Plugin::Web::Streaming::Writer->new(
$self,
$writer
);
$code->($longpoll_ctx);
}
);
}
package Amon2::Plugin::Web::Streaming::Writer;
sub new {
my ($class, $c, $writer) = @_;
bless {ctx => $c, writer => $writer}, $class;
}
sub write_json {
my ($self, $data) = @_;
my $json = $self->{ctx}->render_json($data)->content;
$self->{writer}->write($json);
}
sub close {
my ($self) = @_;
$self->{writer}->close();
}
1;
__END__
=head1 NAME
( run in 0.836 second using v1.01-cache-2.11-cpan-437f7b0c052 )