How can I get the port that Mojolicious :: Lite chooses?

Joel Berger has published this small program to start a web server to serve local files , and it works just fine:

use Mojolicious::Lite;

@ARGV = qw(daemon);

use Cwd;
app->static->paths->[0] = getcwd;

any '/' => sub {
    shift->render_static('index.html');
    };

app->start;

I pre-populated the command line in @ARGVbecause I forgot to do this. When it starts, a message appears in it indicating which port he selected using 3000, if possible:

$ perl ~/bin/mojo_cwd
[Fri Mar 29 19:14:09 2013] [info] Listening at "http://*:3000".
Server available at http://127.0.0.1:3000.

I would like this port to be programmed, so the test suite can know where to look for it, and I would prefer not to do this, breaking the output. None of my experiments were useful for this, and I think that I have always been in the wrong direction. It seems that he does not select the port before it starts, and as soon as I call start, this is its end.

.

. HTTP, Mojo, . , - , - .

+5
2

, daemon 3000 , . Test::Mojo, , - Mojo::Server::Daemon script.

use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::Server::Daemon;

get '/' => {text => 'Hello World!'};

my $port   = Mojo::IOLoop->generate_port;
my $daemon = Mojo::Server::Daemon->new(
  app    => app,
  listen => ["http://*:$port"]
);
$daemon->run;
+7

--listen , :

use Mojolicious::Lite;

@ARGV = qw(daemon --listen http://*:5000);

use Cwd;
app->static->paths->[0] = getcwd;

any '/' => sub {
    shift->render_static('index.html');
    };

app->start;

$self->tx->local_port:

#!/usr/bin/env perl
use Mojolicious::Lite;

@ARGV = qw(daemon --listen http://*:5000);

use Cwd;
app->static->paths->[0] = getcwd;

any '/' => sub {
    my $self = shift;

    $self->render_text('port: '. $self->tx->local_port);
    };

app->start if $ENV{MOJO_MODE} ne 'test';

1;

Mojolicious Test::Mojo, , , t/test_mojo.t:

use strict;
use warnings;

use feature 'say';

use Test::More;
use Test::Mojo;

$ENV{MOJO_MODE} = 'test';

require "$FindBin::Bin/../test_mojo.pl";

my $t = Test::Mojo->new;
$t->get_ok('/')->status_is(200)->content_is('port: '.$t->tx->remote_port);

say 'local port: '. $t->tx->local_port; #as seen from the user-agent perspective
say 'remote port:'. $t->tx->remote_port;
done_testing();

, , , , .

+4

All Articles