Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created February 5, 2012 02:14
Show Gist options
  • Save postmodern/1742022 to your computer and use it in GitHub Desktop.
Save postmodern/1742022 to your computer and use it in GitHub Desktop.
A WEBrick shell server with async output
require 'webrick'
class Server < WEBrick::HTTPServlet::AbstractServlet
def self.start(port,host=nil)
server = WEBrick::HTTPServer.new(:Host => host, :Port => port)
server.mount '/', self
trap('INT') { server.shutdown }
server.start
end
def self.shell
@@shell ||= begin
io = IO.popen(ENV['SHELL'],'r+')
io.extend AsyncRead
io
end
end
def do_POST(request,response)
self.class.shell.puts request.query['cmd']
response.status = 200
end
def do_GET(request,response)
response.status = 200
response.chunked = true
response.body = self.class.shell
end
module AsyncRead
def read(length)
begin
read_nonblock(length)
rescue IO::WaitReadable
IO.select([self])
retry
end
end
end
end
Server.start 1337
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment