perlhttpnonblockinglwplwp-useragent

Perl fire-and-forget HTTP request


This is not the same as a background/asynchronous HTTP request.

Is there a way to fire an HTTP PUT request and not wait on response or determination of success/failure?

My codebase is single-threaded and single-process.

I'm open to monkey-patching LWP::UserAgent->request if needed.


Solution

  • You could just abandon processing the response when the first data come in:

    use LWP::UserAgent;
    
    my $ua = LWP::UserAgent->new;
    my $resp = $ua->put('http://example.com/', ':content_cb' => sub { die "break early" });
    print $resp->as_string;
    

    You might also create a request using HTTP::Request-new('PUT',...)->as_string, create a socket with IO::Socket::IP->new(...) or (for https) IO::Socket::SSL->new(...) and send this request over the socket - then leave the socket open for a while while doing other things in your program.

    But the first approach with the early break in the :content_cb is probably simpler. And contrary to crafting and sending the request yourself it guarantees that the server at least started to process your request since it started to send a response back.