Last active
January 5, 2017 12:47
-
-
Save xsawyerx/2f02f48295bad158ddfa601df20ceda7 to your computer and use it in GitHub Desktop.
Dancer2 asynchronous file serving without `send_file` with extra stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If we didn't care about serving it line by line and encoding this in JSON, the following could have been used instead:
send_file
automatically uses the asynchronous file serving if it's available.