Skip to content

Instantly share code, notes, and snippets.

@bimmerlabs bimmerlabs/myapp_broken.pl
Last active Jul 13, 2018

Embed
What would you like to do?
Subprocess error: Connection already closed when using a line like "if (defined $self->param('foo') { ... }" and the param is not defined
#!/usr/bin/env perl
use Mojolicious::Lite;
# it turns out a race condition was being caused, that accidentally 'won' every time before -
# but the updated Mojolicious made the broken code apparent. This no longer works:
get '/' => sub {
my $self = shift;
$self->render_later;
Mojo::IOLoop->subprocess(
sub {
my $subprocess = shift;
my $template;
# if you uncomment this line so param('foo) is defined, it works
# $self->param(foo => '');
if (defined $self->param('foo')) {
say $self->param('foo');
$template = 'foo';
}
else {
say 'there is no foo';
$template = 'index';
}
return ($template);
},
sub {
my ($subprocess, $err, $template) = @_;
say "Subprocess error: $err" and $self->render('index')
if $err;
$self->render($template);
}
);
};
app->start;
__DATA__
@@ foo.html.ep
% layout 'default';
% title 'Welcome';
<%= param 'foo' %>
@@ index.html.ep
% layout 'default';
% title 'Welcome';
There is no foo.
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
#!/usr/bin/env perl
use Mojolicious::Lite;
# by using Mojolicious::Plugin::Subprocess, the race condition is avoided. The code is shorter/cleaner too.
plugin 'Subprocess';
get '/' => sub {
my $self = shift;
$self->render_later;
$self->subprocess(
sub {
my $subprocess = shift;
my $template;
if (defined $self->param('foo')) {
say $self->param('foo');
$template = 'foo';
}
else {
say 'there is no foo';
$template = 'index';
}
return ($template);
},
sub {
my ($subprocess, $template) = @_;
$self->render($template);
}
);
};
app->start;
__DATA__
@@ foo.html.ep
% layout 'default';
% title 'Welcome';
<%= param 'foo' %>
@@ index.html.ep
% layout 'default';
% title 'Welcome';
There is no foo.
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.