Skip to content

Instantly share code, notes, and snippets.

@xsawyerx
Last active January 5, 2017 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xsawyerx/2f02f48295bad158ddfa601df20ceda7 to your computer and use it in GitHub Desktop.
Save xsawyerx/2f02f48295bad158ddfa601df20ceda7 to your computer and use it in GitHub Desktop.
Dancer2 asynchronous file serving without `send_file` with extra stuff
use Dancer2;
use Text::CSV_XS qw< csv >;
use Path::Tiny qw< path >;
use JSON::MaybeXS qw< encode_json >;
# Create a CSV parser
my $csv = Text::CSV_XS->new({
'binary' => 1,
'auto_diag' => 1,
});
get '/' => sub {
# Return async response
delayed {
# Start async
flush;
# Read each row and stream it in JSON
my $fh = path('filename.csv')->openr_utf8;
while ( my $row = $csv->getline($fh) ) {
content encode_json $row;
}
# Close connection
done;
};
};
@xsawyerx
Copy link
Author

xsawyerx commented Jan 4, 2017

If we didn't care about serving it line by line and encoding this in JSON, the following could have been used instead:

get '/' => sub {
    send_file 'filename.csv';
};

send_file automatically uses the asynchronous file serving if it's available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment