Stream console output through HTTP (with Ruby)

走远了吗. 提交于 2019-11-30 00:37:51

If you're on a synchronous server (i.e. Mongrel, Unicorn, not Thin), you can just return an IO object:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log')
end

If that doesn't work (if you're on Thin, for instance), you can use the new streaming API:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log') do |io|
    stream do |out|
      io.each { |s| out << s }
    end
  end
end

You can also use the bcat gem, which will colorize your output, if it contains ANSI color codes:

require 'sinatra'
require 'bcat'

get '/log' do
  command = %[tail -f some.log]
  bcat = Bcat.new(command, :command => true)
  bcat.to_app.call(env)
end

Note: For infinitely running process you'll have to take care of killing the process yourself if someone closes the connection. With the first solution some servers might take care of that for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!