I am making a simple rack application that grant access to secured files after an authentication.
As the data in the files is sensitive, they are located in a non-public folder of the application.
For now, after checking the session data, I just open the file for read and send the content as the body of the response.
It feels ugly and must be very ressource consuming for larger files.
Example response:
[ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, File.open( file ).read() ]
I looked into Rack::Sendfile, but as far as I understand it, it is a middleware and cannot send files from inside the application itself.
What would the most efficient way to send non-public binary files from a Rack application?
A Rack response body must respond to #each{|d|}
. So you could stream the response like this:
class FileStreamer
def initialize(path)
@file = File.open(path)
end
def each(&blk)
@file.each(&blk)
ensure
@file.close
end
end
Usage:
[ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, FileStreamer.new(file) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With