Last active
December 10, 2015 22:22
-
-
Save preaction/a6736b06a079090d4ecd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojolicious::Lite; | |
use Mojo::IOLoop; | |
use Mojo::IOLoop::Stream; | |
websocket '/' => sub { | |
my ( $c ) = @_; | |
my ( $stream, $id ); | |
$c->on( message => sub { | |
my ( $c, $msg ) = @_; | |
if ( $stream ) { | |
$stream->close; | |
undef $stream; | |
} | |
$c->app->log->info( "Got command: $msg" ); | |
if ( open my $fh, '-|', $msg ) { | |
my $stream = Mojo::IOLoop::Stream->new( $fh ); | |
$stream->on( read => sub { | |
my ( $stream, $bytes ) = @_; | |
$c->app->log->debug( "Sending output: $bytes" ); | |
$c->send( $bytes ); | |
} ); | |
$id = Mojo::IOLoop->singleton->stream( $stream ); | |
$c->on( finish => sub { | |
my ( $c ) = @_; | |
$c->app->log->debug( "Closing stream" ); | |
undef $stream; | |
# Either of these two lines makes the app freeze | |
#Mojo::IOLoop->singleton->remove( $id ); | |
#$stream->close; | |
} ); | |
} | |
else { | |
$c->send( "Could not execute '$msg': $!" ); | |
} | |
} ); | |
}; | |
app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment