Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

AnyEvent::HTTPD::Request Dynamic Async Response

by sectokia (Pilgrim)
on Jun 05, 2022 at 23:27 UTC ( #11144418=perlquestion: print w/replies, xml ) Need Help??

sectokia has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am using AnyEvent::HTTPD / AnyEvent::HTTP::Request. I want to be able to do async IO when a request comes in, and have ability to set the response status, and response content-type, based on the result of that async IO.

However I cannot figure out any way to do this. All the examples I have see all require the content-type specified up-front - and their behavior is that the client is immediately sent response headers (with 200 status and content-type), and then async IO callback is provided, such that only the response body can be asynchronously generated. Example based on AnyEvent::HTTPD::Request doc:

$req->respond ({ content => ['text/plain', sub { my ($data_cb) = @_; # 200 / text/plain already sent to client by now... # do async io that eventually calls the call back... myPromise()->then(sub{ $data_cb->("OK"); # Too late to change content-type or status co +de here.. $data_cb->(); })->catch(sub{ $data_cb->("Failed"); # Or here... $data_cb->(); }); } });

Any ideas? Or should I change to a different 'framework'? Thanks!

Replies are listed 'Best First'.
Re: AnyEvent::HTTPD::Request Dynamic Async Response
by Corion (Patriarch) on Jun 06, 2022 at 06:23 UTC

    You can respond even later, as the code in delayed_2_example shows:

    $httpd->reg_cb ( '/test' => sub { my ($httpd, $req) = @_; $t = AnyEvent->timer (after => 2, cb => sub { my $txt = "CPU info:\n\n" . `cat /proc/cpuinfo`; $req->respond ([200, "ok", { 'Content-Type' => 'text/plain' } +, $txt]); }); }, );

    So you can't "respond" until you have a meaningful content type, but that's OK as you can delay your response.

      Duh, Not sure why I thought you couldn't do that... Thanks.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11144418]
Approved by kcott
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2023-12-02 02:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (13 votes). Check out past polls.

    Notices?