Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving non-public binary files from a Rack application

Tags:

ruby

rack

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?

like image 665
Eric Avatar asked Oct 07 '22 03:10

Eric


1 Answers

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) ]
like image 134
simonmenke Avatar answered Oct 10 '22 02:10

simonmenke