Ruby 带报头的Sinatra流式响应
我想通过Sinatra应用程序代理远程文件。这需要将带有头的HTTP响应从远程源流回到客户端,但我不知道如何在Ruby 带报头的Sinatra流式响应,ruby,sinatra,Ruby,Sinatra,我想通过Sinatra应用程序代理远程文件。这需要将带有头的HTTP响应从远程源流回到客户端,但我不知道如何在Net::HTTP#get_response提供的块中使用流API时设置响应头 例如,这不会设置响应头: get '/file' do stream do |out| uri = URI("http://manuals.info.apple.com/en/ipad_user_guide.pdf") Net::HTTP.get_response(uri) do |fil
Net::HTTP#get_response
提供的块中使用流API时设置响应头
例如,这不会设置响应头:
get '/file' do
stream do |out|
uri = URI("http://manuals.info.apple.com/en/ipad_user_guide.pdf")
Net::HTTP.get_response(uri) do |file|
headers 'Content-Type' => file.header['Content-Type']
file.read_body { |chunk| out << chunk }
end
end
end
我可能是错的,但是在考虑过这一点之后,我发现当从
流
帮助程序块内部设置响应头时,这些头不会应用到响应中,因为该块的执行实际上被延迟了。因此,在开始执行之前,可能会计算块并设置响应头
一种可能的解决方法是在流式返回文件内容之前发出HEAD请求
例如:
get '/file' do
uri = URI('http://manuals.info.apple.com/en/ipad_user_guide.pdf')
# get only header data
head = Net::HTTP.start(uri.host, uri.port) do |http|
http.head(uri.request_uri)
end
# set headers accordingly (all that apply)
headers 'Content-Type' => head['Content-Type']
# stream back the contents
stream do |out|
Net::HTTP.get_response(uri) do |f|
f.read_body { |ch| out << ch }
end
end
end
get'/file'do
uri=uri('http://manuals.info.apple.com/en/ipad_user_guide.pdf')
#仅获取标题数据
head=Net::HTTP.start(uri.host,uri.port)do | HTTP|
http.head(uri.request\uURI)
结束
#相应地设置标题(所有适用项)
标题“内容类型”=>head['Content-Type']
#倒流内容
流出|
Net::HTTP.get_response(uri)do|f|
f、 读出正文
get '/file' do
uri = URI('http://manuals.info.apple.com/en/ipad_user_guide.pdf')
# get only header data
head = Net::HTTP.start(uri.host, uri.port) do |http|
http.head(uri.request_uri)
end
# set headers accordingly (all that apply)
headers 'Content-Type' => head['Content-Type']
# stream back the contents
stream do |out|
Net::HTTP.get_response(uri) do |f|
f.read_body { |ch| out << ch }
end
end
end