问题
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
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?
Edit:
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.
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.
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.
回答1:
This seems to come down to a problem with running code after the response is sent. Not a very easy task:
What's the fastest way for a true sinatra(ruby/rack) 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
Seems very "hacky", but I question the point of being able to remotely shutdown a web server via a call to a URI anyway. ;-)
来源:https://stackoverflow.com/questions/19523889/sinatra-terminate-server-from-request