Net :: HTTP :: Server在读取文件时失败

时间:2013-09-26 19:41:22

标签: ruby httpserver

我正在尝试编写一个非常简单的HTTP服务器,它会在每个请求中返回文件的下500行。如果我尝试读取文件,服务器将失败。

这是我的计划:

#!/usr/bin/env ruby

require 'rubygems'
require 'net/http/server'
require 'pp'

file = File.foreach("data/all.txt").each_slice(500)

headers = {'Content-Type' => 'text/plain'}
Net::HTTP::Server.run(:port => 2000) do |request, stream|
    [200, headers, file.next]
end

如果我发出请求,我会从文件中获得前500行,但是我在控制台上看到了这一行:

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/generator.rb:132:in`call'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/generator.rb:132:in`next'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/generator.rb:190:in`next' ./urlServer.rb:12
/Library/Ruby/Gems/1.8/gems/net-http-server-0.2.2/lib/net/http/server/daemon.rb:122:in`call'
/Library/Ruby/Gems/1.8/gems/net-http-server-0.2.2/lib/net/http/server/daemon.rb:122:in`serve'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:211:in`start'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:208:in`initialize'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:208:in`new'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:208:in`start'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:198:in`initialize'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:198:in`new'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/gserver.rb:198:in`start'
/Library/Ruby/Gems/1.8/gems/net-http-server-0.2.2/lib/net/http/server/server.rb:42:in`run' ./urlServer.rb:11

所有进一步的请求都失败了。

如何修复此程序?

1 个答案:

答案 0 :(得分:1)

file变量中的枚举器到达然后结束时,next方法将引发StopIteration异常,但您没有拯救它,因此这可能是问题所在。< / p>

您可能希望将其包装在begin-rescue块中,例如:

Net::HTTP::Server.run(:port => 2000) do |request, stream|
  begin
    body = file.next
  rescue StopIteration
    body = []
  end

  [200, headers, body]
end