Skip to content

Instantly share code, notes, and snippets.

@miyagawa
Created January 14, 2010 13:14
Show Gist options
  • Save miyagawa/277148 to your computer and use it in GitHub Desktop.
Save miyagawa/277148 to your computer and use it in GitHub Desktop.
Needs github Plack topic/refactor-loader branch. Inspired by http://github.com/rtomayko/shotgun
package Plack::Server::Shotgun;
use strict;
use HTTP::Server::PSGI;
use Storable;
use Try::Tiny;
sub new {
my($class, %args) = @_;
bless { args => \%args }, $class;
}
sub run_with_reload {
my($self, $builder, %args) = @_;
# TODO support other servers?
HTTP::Server::PSGI->new(%{$self->{args}})->run($self->_app($builder));
}
sub _app {
my($self, $builder) = @_;
return sub {
my $env = shift;
pipe my $read, my $write;
my $pid = fork;
if ($pid > 0) {
# parent
close $write;
my $res = Storable::thaw(join '', <$read>);
close $read;
waitpid($pid, 0);
return $res;
} else {
# child
close $read;
# TODO buffer streaming
my $res = $builder->()->($env);
my @body;
Plack::Util::foreach($res->[2], sub { push @body, $_[0] });
$res->[2] = \@body;
print {$write} Storable::freeze($res);
close $write;
exit;
}
};
}
sub run { die "Run this by `plackup -r -s Shotgun`" }
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment