Skip to content

Commit 4c994ac

Browse files
author
Jan Henning Thorsen
committed
Add example/tail.pl
1 parent d4e1261 commit 4c994ac

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

example/tail.pl

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use Mojolicious::Lite;
2+
use Mojo::IOLoop::ReadWriteFork;
3+
4+
# NOTE!
5+
# THIS APPLICATION IS A BAD IDEA.
6+
# IT SHOULD ONLY SERVER AS AN EXAMPLE.
7+
8+
get '/tail/:name', sub {
9+
my $self = shift->render_later;
10+
my $file = '/var/log/' .$self->stash('name');
11+
my $fork = Mojo::IOLoop::ReadWriteFork->new;
12+
13+
# The request will end after 15 seconds of inactivity.
14+
# The line below can be used to increase that timeout,
15+
# but it is required to make sure we don't run the
16+
# "tail" process forever.
17+
# Mojo::IOLoop->stream($self->tx->connection)->timeout(60);
18+
19+
# Make sure the object does not go out of scope
20+
$self->stash(fork => $fork);
21+
22+
$self->write_chunk("# tail -f $file\n");
23+
24+
# Make sure we kill "tail" after the request is finished
25+
# NOTE: This code might be to simple
26+
$self->on(finish => sub {
27+
my $self = shift;
28+
my $fork = $self->stash('fork') or return;
29+
app->log->debug("Ending tail process");
30+
$fork->kill;
31+
});
32+
33+
# Write data from "tail" directly to browser
34+
$fork->on(read => sub {
35+
my($fork, $buffer) = @_;
36+
$self->write_chunk($buffer);
37+
});
38+
39+
# Start the tail program.
40+
# "-n50" is just to make sure we have enough data to make the browser
41+
# display anything. It should work just fine from curl, Mojo::UserAgent,
42+
# ..., but from chrome, ie, ... we need a big chunk of data before it
43+
# gets visible.
44+
$fork->start(program => 'tail', program_args => ['-f', '-n50', $file]);
45+
};
46+
47+
app->start;

lib/Mojo/IOLoop/ReadWriteFork.pm

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ and STDOUT are more than welcome.
1818
1919
=head1 SYNOPSIS
2020
21+
=head2 Standalone
22+
2123
my $fork = Mojo::IOLoop::ReadWriteFork->new;
2224
my $cat_result = '';
2325
@@ -41,6 +43,10 @@ and STDOUT are more than welcome.
4143
conduit => 'pty',
4244
);
4345
46+
=head2 In a Mojolicios::Controller
47+
48+
See L<https://github.com/jhthorsen/mojo-ioloop-readwritefork/tree/master/example/tail.pl>.
49+
4450
=cut
4551

4652
use Mojo::Base 'Mojo::EventEmitter';

0 commit comments

Comments
 (0)