EventMachineでHTTPd

重い処理はバックグラウンドに回すのが正解なのかな。
基本的にmutableなオブジェクトの共有はNGな気がするな。

#!/usr/bin/env ruby
require 'rubygems'
require 'eventmachine'

class HTTP < EM::Connection
  def receive_data(data)
    operation = lambda do
      # 重い処理、ごにょごにょ…

      (<<-EOS).gsub(/\r?\n/,"\r\n")
HTTP/1.1 200 OK

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    test
  </body
</html>
      EOS
    end # operation

    callback = lambda do |res|
      send_data(res)
      close_connection_after_writing 
    end

    EM.defer(operation, callback)
  end # receive_data
end

EM.run do
  EM.start_server('0.0.0.0', 80, HTTP)
end