Debian Codegraph @

samples/large_response_example

raw
1 #!/opt/perl/bin/perl
2 use common::sense;
3 use AnyEvent;
4 use AnyEvent::HTTPD;
5 use AnyEvent::AIO;
6 use IO::AIO;
7
8 my $cvar = AnyEvent->condvar;
9
10 my $httpd = AnyEvent::HTTPD->new (port => 19090);
11
12 my $SEND_FILE = defined $ARGV[0] ? $ARGV[0] : 'bshttp.png';
13 my $mime = `file -i $SEND_FILE`;
14 $mime =~ s/^(.*?): //;
15 $mime =~ s/\r?\n$//;
16
17 print "going to send $SEND_FILE: $mime\n";
18
19 sub send_file {
20 my ($req) = @_;
21
22 my $fh;
23 my $last_pos = 0;
24
25 print "going to open $SEND_FILE...\n";
26
27 # use IO::AIO to async open the file
28 aio_open $SEND_FILE, O_RDONLY, 0, sub {
29 $fh = shift;
30
31 unless ($fh) {
32 warn "couldn't open $SEND_FILE: $!\n";
33 $data_cb->(); # stop sending data...
34 return;
35 }
36
37 my $size = -s $fh;
38
39 print "opened $SEND_FILE, $size bytes big!\n";
40
41 # make a reader callback, that will be called
42 # whenever a chunk of data was written out to the kernel
43 my $get_chunk_cb = sub {
44 my ($data_cb) = @_;
45
46 if ($data_cb) {
47 print "get next chunk, $last_pos of $size!\n";
48 } else {
49 print "sent last chunk, no more required!\n";
50 }
51
52 return unless $data_cb; # in case the connection went away...
53
54 my $chunk = '';
55
56 # use IO::AIO again, to async read from disk
57 # you decide what chunks you want to send btw.
58 # here we send 4096 bytes on each chunk read.
59 aio_read $fh, $last_pos, 4096, $chunk, 0, sub {
60 if ($_[0] > 0) {
61 $last_pos += $_[0];
62 print "read $_[0] bytes, sending them...\n";
63 $data_cb->($chunk); # when we got another chunk, push it
64 # over the http connection;
65 $chunk = '';
66
67 # and here we just return, and wait for the next call to
68 # $get_chunk_cb when the data is in the kernel.
69
70 } else {
71 $data_cb->(); # stop sending data (in case of error or EOF)
72 return;
73 }
74 };
75 };
76
77 $req->respond (
78 [
79 200, 'ok', {
80 'Content-Type' => $mime,
81 # 'Content-Length' => $size
82 },
83 $get_chunk_cb
84 ]
85 );
86 };
87 }
88
89 $httpd->reg_cb (
90 '' => sub {
91 my ($httpd, $req) = @_;
92 $req->respond ({ content => ['text/html', <<'CONT']});
93 <html><body><h1>Large Download Example!</h1>
94 <a href="/test">download file</a>
95 </body></html>
96 CONT
97 },
98 '/test' => sub {
99 my ($httpd, $req) = @_;
100 $httpd->stop_request;
101
102 print "sending file ...\n";
103 send_file ($req);
104 },
105 );
106
107 $cvar->wait;