【问题标题】:Return Sinatra response before stopping EventMachine在停止 EventMachine 之前返回 Sinatra 响应
【发布时间】:2012-11-21 01:18:38
【问题描述】:

我在事件机器中使用 Sinatra,我想在收到 DELETE 请求后关闭服务器并退出,并返回 200 OK。但是,现在我无法做到这一点,并且总是在退出之前返回一个空响应。我将如何实现这一目标?以下是相关代码:

EM.run do
  class Server < Sinatra::Base
    delete '*' do
      EM.defer proc{ halt 200 }, proc{ EM.stop }
     end
  end

  Server.run!
end

我得到一个空回复,并得到以下堆栈跟踪:

/Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/sinatra-1.3.3/lib/sinatra/base.rb:803:in `throw': uncaught throw `halt' in thread 0x7fa4225f2020 (ThreadError)
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/sinatra-1.3.3/lib/sinatra/base.rb:803:in `halt'
    from instant-markdown-d.rb:39:in `DELETE *'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1037:in `call'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1037:in `spawn_threadpool'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1033:in `initialize'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1033:in `new'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1033:in `spawn_threadpool'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:1023:in `defer'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/thin-1.5.0/lib/thin/connection.rb:51:in `process'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/thin-1.5.0/lib/thin/connection.rb:39:in `receive_data'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:187:in `run_machine'
    from /Users/syeo/.rvm/gems/ruby-1.8.7-p352@instant-markdown-d/gems/eventmachine-1.0.0/lib/eventmachine.rb:187:in `run'
    from instant-markdown-d.rb:10

我也尝试了许多类似的方法,但找不到发送 200 的方法,然后关闭服务器。

【问题讨论】:

  • 这行得通吗? EM.defer proc{ status 200; EM.stop }。您不一定需要回调。我仍然想知道您为什么要使用 EM.defer 来表示该 sn-p。
  • 谢谢@Kashyap,但没有骰子。当我这样做时会发生什么,我没有得到堆栈跟踪,但客户端得到一个空响应,并且服务器没有关闭。我使用EM.defer 的原因是因为我认为EM.stop 在sinatra 有机会完成响应之前就被执行了。

标签: sinatra eventmachine


【解决方案1】:

最终这样做了:

EM.run do
  class Server < Sinatra::Base
    delete '*' do
      EM.add_timer(0.2) do
        EM.stop
        exit
      end
      status 200
    end
  end

  Server.run!
end

这是一个 hack,但至少有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多