Plack/Example/ServerEvents.pm untested

filter: Statementstmt 0.0% 0 / 45 Branchbran 0.0% 0 / 6 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 5 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 57 CC 4 SCAR 24.0
CC
4
Cov
0%
countdown
20.0
BEGIN
2.0
BEGIN
2.0
CRAP 11.0
1 package Plack::Example::ServerEvents;
2 use strict;
3 use AnyEvent;
4 use HTTP::ServerEvent;
5  
6 =head1 NAME
7  
8 Plack::Example::ServerEvents - Sample Server-Sent Events server
9  
10 =head1 SYNOPSIS
11  
12 plackup -MPlack::Example::ServerEvents -e "Plack::Example::ServerEvents->countdown"
13  
14 =cut
15  
16 use vars qw($VERSION);
17 $VERSION = '0.02';
18  
19 my $html= join "", <DATA>;
20  
21 # Creates a PSGI responder
22 sub countdown {
23 my $app= sub {
24 my $env = shift;
25  
26 if( $env->{PATH_INFO} ne '/events' ) {
27 # Send the JS+HTML
28 return [ 200, ['Content-Type', 'text/html'], [$html] ]
29 };
30  
31 if( ! $env->{"psgi.streaming"}) {
32 my $err= "Server does not support streaming responses";
33 warn $err;
34 return [ 500, ['Content-Type', 'text/plain'], [$err] ]
35 };
36  
37 # immediately starts the response and stream the content
38 return sub {
39 my $responder = shift;
40 my $writer = $responder->(
41 [ 200, [ 'Content-Type', 'text/event-stream' ]]);
42 my $countdown= 10;
43
44 my $w; $w= AnyEvent->timer(
45 after => 1,
46 interval => 1,
47 cb => sub {
48 $countdown--;
49 if (0 < $countdown) {
50 my $event= HTTP::ServerEvent->as_string(
51 data => $countdown,
52 event => 'tick',
53 );
54  
55 $writer->write($event);
56 } else {
57 warn "Boom";
58 undef $w;
59 $writer->close;
60 }
61 }
62 );
63 };
64 };
65  
66 };
67  
68 1;
69  
70 =head1 SEE ALSO
71  
72 The source code of this module
73  
74 L<HTTP::ServerEvent>
75  
76 =head1 AUTHOR
77  
78 Max Maischein C<corion@cpan.org>
79  
80 =head1 COPYRIGHT (c)
81  
82 Copyright 2013-2013 by Max Maischein C<corion@cpan.org>.
83  
84 =head1 LICENSE
85  
86 This module is released under the same terms as Perl itself.
87  
88 =cut
89  
90 __DATA__