Serving non-public binaries from the Rack application

I am making a simple rack that provides access to protected files after authentication.
Since the data in the files is sensitive, they are located in the non-public folder of the application.

Now, after checking the session data, I just open the file to read and send the contents as the response body.
It feels ugly and must consume resources for large files very much.

Answer example:

[ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, File.open( file ).read() ] 

I looked at Rack :: Sendfile , but as far as I understand, it is middleware and cannot send files from the application by itself.

What would be the most efficient way to send non-public binaries from a Rack app?

+4
source share
2 answers

A The reaction body of the rack should respond to #each{|d|} . So you could pass the answer like this:

 class FileStreamer def initialize(path) @file = File.open(path) end def each(&blk) @file.each(&blk) ensure @file.close end end 

Using:

 [ "200", {"Content-Type"=> MIME::Types.type_for(file).first.to_s }, FileStreamer.new(file) ] 
+4
source

Alternatively, if you use a Rack :: Response object , you can do something like this:

 response = Rack::Response.new file = open(path_to_binary_file, "rb") # other stuff… mime = Mime.mime_type(::File.extname(file.path), 'text/html') response.headers.merge!( "Content-Type" => mime ) if mime response.write file response.finish 
0
source

Source: https://habr.com/ru/post/1443163/


All Articles