Snippets

Brian Medley Fancy file tai'r that will POST each line somewhere

Created by Brian Medley last modified
#!/opt/perl

use Mojo::Base -strict;

use Mojo::UserAgent;
use Mojo::IOLoop;

use IO::File;

my $fh = IO::File->new();
unless ($fh->open("< tail.me")) {
    die;
}

$fh->autoflush(1);
$fh->sysseek(0, 2);

my @lines = ();

my $reactor = Mojo::IOLoop->singleton->reactor;
$reactor->io($fh =>
    sub {
        state $line = undef;

        my $reactor = shift;

        while (my $ret = sysread($fh, my $buf, 1)) {
            $line .= $buf;

            if ("\n" eq $buf) {
                warn("> $line");

                push(@lines, $line);

                $line = undef;
            }
        }
    }
)->watch($fh, 1, 0);

my $id = $reactor->recurring(60 => sub {
    my $ua = Mojo::UserAgent->new;
    
    foreach my $line (@lines) {
        warn(">> $line");
        $ua->post('http://127.0.0.1:300/v1/api/parse' => json => {line => $line} => sub {});
    }

    @lines = ();
});

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.