perlmojoliciousmojo-useragent

How to user Mojo::UserAgent's connect_timeout


Perl newbie here. I have a line of code:

my $api_data = decode_json( $ua->get($url)->res->body );

where $ua = Mojo::UserAgent->new. On occasion, the request may hang (indefinitely) and I'd like to specify a connection timeout.

The documentation provides an example, but I'm not exactly sure how to incorporate it correctly into my statement.

How should I use connect_timeout in this case? I understand that Mojo specifies a default connection timeout value (10), but I'd rather specify it explicitly in the code.


Solution

  • The documentation shows that connect_timeout can be used as both a getter and a setter:

    my $timeout = $ua->connect_timeout;    # getter
    $ua         = $ua->connect_timeout(5); # setter
    

    The setter returns the Mojo::UserAgent object it's called on so that it can be chained with other methods.

    So you could do:

    my $ua = Mojo::UserAgent->new;
    
    my $api_data = decode_json( $ua->connect_timeout(42)->get($url)->res->body );
    

    But you're not required to chain methods, so I would recommend a more readable version:

    my $ua = Mojo::UserAgent->new;
    $ua->connect_timeout(42);
    
    my $api_data = decode_json( $ua->get($url)->res->body );