1

I am building a web application using sinatra. It basically takes a url of a page as request and fetches the link to media file from the page. Once that is retrieved it opens a stream to the media file. Now I want to send this stream as http response to client. I tried to do the following.

get '/' do
  url=PM.link(params[:url])
  puts url
  buf=nil
  open(url, 'rb') do |rf|
    while(buf=rf.read(1024)) do
      stream do |out|
        out << buf
      end
    end  
  end
end

and also this

get '/' do
  url=PM.link(params[:url])
  puts url
  buf=nil
  open(url, 'rb') do |rf|
    stream do |out|
      out.write rf.read
    end  
  end
end

But neither work. I tried storing the media file in a local file it stores it properly. But when I try to write it to out stream it responds with no data. Am I missing something? Or sinatra doesn't allow writing binary from one stream to other.

4

1 回答 1

0

一个问题是您没有正确提出请求。要http request做到这一点:

uri = URI.parse(yoururl)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)

然后你可以对响应做你想做的事。在您的情况下,它可能如下所示:

get '/' do
  url=PM.link(params[:url])
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)
  response = http.request(request)

end

但是,这不适用于流式传输。这是一个可以帮助您的教程:http: //www.intridea.com/blog/2012/5/24/building-streaming-rest-apis-with-ruby#

于 2012-12-31T08:20:07.017 回答