在Rack应用程序上提供存储在S3上的HTML文件

时间:2013-01-12 16:10:02

标签: ruby static sinatra rack

假设我在S3上存储了一些HTML文档:

我想用Rack(最好是Sinatra)应用程序来提供这些服务,映射以下路线:

get "/posts/:id" do
 render "http://alan.aws-s3-bla-bla.com/posts/#{params[:id]}.html"
end

get "/posts/:posts_id/comments/:comments_id" do
 render "http://alan.aws-s3-bla-bla.com/posts/#{params[:posts_id]}/comments/#{params[:comments_id}.html"
end

这是个好主意吗?我该怎么做?

1 个答案:

答案 0 :(得分:1)

当你抓住文件时显然会有等待,所以你可以缓存它或设置etags等来帮助解决这个问题。我想这取决于你想要等待多长时间以及它的访问频率,它的大小等是否值得在本地或远程存储HTML。只有你可以解决这个问题。

如果块中的最后一个表达式是一个将自动呈现的字符串,那么只要您将该文件作为字符串打开,就不需要调用render

以下是获取外部文件并将其放入临时文件的方法:

require 'faraday'
require 'faraday_middleware'
#require 'faraday/adapter/typhoeus' # see https://github.com/typhoeus/typhoeus/issues/226#issuecomment-9919517 if you get a problem with the requiring
require 'typhoeus/adapters/faraday'

configure do
  Faraday.default_connection = Faraday::Connection.new( 
    :headers => { :accept =>  'text/plain', # maybe this is wrong
    :user_agent => "Sinatra via Faraday"}
  ) do |conn|
    conn.use Faraday::Adapter::Typhoeus
  end
end

helpers do
  def grab_external_html( url )
    response = Faraday.get url # you'll need to supply this variable somehow, your choice
    filename = url # perhaps change this a bit
    tempfile = Tempfile.open(filename, 'wb') { |fp| fp.write(response.body) }
  end
end

get "/posts/:whatever/" do
  tempfile = grab_external_html whatever # surely you'd do a bit more here…
  tempfile.read
end

这可能有用。您可能还想考虑关闭该临时文件,但垃圾收集器和操作系统应该处理它。