View difference between Paste ID: 1Ncu5Dnm and RZhnfWrh
SHOW: | | - or go back to the newest paste.
1-
package Mojolicious::Plugin::MySub;
1+
package Mojolicious::Plugin::EventSource;
2
use Mojo::Base 'Mojolicious::Plugin';
3
4
sub register {
5
   my $self = shift;
6
   my $app  = shift;
7
   my $conf = shift;
8-
   $app->helper( mysub => sub { 1 } );
8+
9
   $conf->{ timeout } ||= 300;
10
11-
1;
11+
   $app->routes->add_shortcut('event_source' => sub {
12
13-
## app.pl
13+
      my $self = shift;
14
      my @pars = map {
15
16
         if(ref $_ eq "CODE") {
17
            my $copy = $_;
18-
plugin 'Mojolicious::Plugin::MySub';
18+
            $_ = sub {
19
               my $self = shift;
20-
mysub '/test' => sub {
20+
               Mojo::IOLoop->stream($self->tx->connection)->timeout($conf->{ timeout });
21
               $self->res->headers->content_type('text/event-stream');
22-
};
22+
               $self->$copy(@_);
23-
app->start;
23+
            };
24
         }
25
         $_;
26
      } @_;
27
28
      $app->routes->get( @_, "" );
29
30
   });
31
32
   $app->helper( 'event_source' => sub { $app->routes->event_source( @_ ) } );
33
34
   $app->helper( 'emit' => sub {
35
      my $self  = shift;
36
      my $event = shift;
37
      my $data  = shift;
38
      $self->write("event:$event\ndata: $data\n\n");
39
   });
40
41
}
42
43
42;
44
45
46
47
#### app.pl
48
49
#!/usr/bin/env perl
50
use Mojolicious::Lite;
51
plugin 'Mojolicious::Plugin::EventSource';
52
53
get '/' => 'index';
54
55
event_source('/events' => sub {
56
  my $self = shift;
57
  print $self->tx, $/;
58
59
  my $id = Mojo::IOLoop->recurring(1 => sub {
60
    my $pips = int(rand 6) + 1;
61
    $self->emit("dice", $pips);
62
  });
63
64
  $self->on(finish => sub { print $/ x 3, "finish!!!", $/ x 3, Mojo::IOLoop->drop($id) });
65
66
});
67
68
app->start;
69
__DATA__
70
71
@@ index.html.ep
72
<!doctype html><html>
73
  <head><title>Roll The Dice</title></head>
74
  <body>
75
    <script>
76
      var events = new EventSource('<%= url_for 'events' %>');
77
78
      // Subscribe to "dice" event
79
      events.addEventListener('dice', function(event) {
80
        document.body.innerHTML += event.data + '<br/>';
81
      }, false);
82
    </script>
83
  </body>
84
</html>