Sinatra - 根据请求终止服务器 [英] Sinatra - terminate server from request

查看:37
本文介绍了Sinatra - 根据请求终止服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从请求中终止 Sinatra 应用程序,例如使用以下路线:

I want to be able to terminate a Sinatra app from a request, e.g. with the following route:

post '/terminate' do
  Thread.current.kill
end

像这样实现它有点突然.我宁愿请求完成,返回 HTTP OK 消息,然后 Sinatra 正常关闭.

Implementing it like this is a bit abrupt. I'd rather the request completed, returned an HTTP OK message, and then Sinatra shut down gracefully.

有没有钩子可以做到这一点?

Is there a hook to do this?

我的应用程序是一个轻量级的模拟服务器,用于接收 webhook 通知.我将在同一台机器上使用多个这样的服务器(不同的端口),所以需要避免任何启动/停止的全局方法.

My application is a lightweight mock server used for receiving webhook notifications. I will be using multiple servers like this on the same machine (different ports), so need to avoid any global methods of starting/stopping.

我的要求是因为每个服务器都必须在自己的 Ruby 实例中运行,因此除了通过 REST 接口之外,我的测试和服务器之间没有任何通信.

My requirement is driven by the fact that each server must run in its own Ruby instance, hence no communication between my tests and the server other than via the REST interface.

我使用默认的 thin 服务器来运行 Sinatra.到目前为止,我的代码只是 Sinatra::Base 的一个子类,从代码中开始使用 run! .这很好也很简单,我可以制作独立的脚本来实例化每个服务器,我只需要一种停止它们的方法.

I'm using the default thin server to run Sinatra. So far my code is just a subclass of Sinatra::Base, started using run! from within the code. This is nice and simple, I can make standalone scripts to instantiate each server, I just need to have a way of stopping them.

推荐答案

这似乎归结为在发送响应之后运行代码的问题.不是一件容易的事:

This seems to come down to a problem with running code after the response is sent. Not a very easy task:

什么是真实的最快方法sinatra(红宝石/机架)after_filter?

也就是说,看起来你可以做这样的事情(虽然我还没有测试过):

That said, it looks like you could do something like this (though I haven't tested it):

post '/terminate' do
  body "I'll be back..."
  # maybe clean things up here...
  logger.info "Received terminate request!"
  Thread.new { sleep 1; Process.kill 'INT', Process.pid }
  halt 200
end

看起来非常hacky",但我质疑无论如何都能通过调用 URI 远程关闭 Web 服务器的意义.;-)

Seems very "hacky", but I question the point of being able to remotely shutdown a web server via a call to a URI anyway. ;-)

这篇关于Sinatra - 根据请求终止服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆