title: Writing a simple webserver in Ruby
body: <p>I want to create an extremely simple web server for development purposes in Ruby (no, don’t want to use ready solutions).</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#!/usr/bin/ruby
  
  require 'socket'
  
  server = TCPServer.new('127.0.0.1', 8080)
  
  while connection = server.accept
    headers = []
    length  = 0
  
    while line = connection.gets
      headers &lt;&lt; line
  
      if line =~ /^Content-Length:\s+(\d+)/i
        length = $1.to_i
      end
  
      break if line == "\r\n"
    end
  
    body = connection.readpartial(length)
  
    IO.popen(ARGV[0], 'r+') do |script|
      script.print(headers.join + body)
      script.close_write
      connection.print script.read
    end
  
    connection.close
  end
  </code></pre>
  
  <p>The idea is to run this script from the command line, providing another script, which will get the request on its standard input, and gives back the complete response on its standard output.</p>
  
  <p>So far so good, but this turns out to be really fragile, as it breaks on the second request with the error:</p>
  
  <pre><code>/usr/bin/serve:24:in `write': Broken pipe (Errno::EPIPE)
      from /usr/bin/serve:24:in `print'
      from /usr/bin/serve:24
      from /usr/bin/serve:23:in `popen'
      from /usr/bin/serve:23
  </code></pre>
  
  <p>Any idea how to improve the above code to be sufficient for easy use?</p>
  
  <p>Versions: Ubuntu 9.10 (2.6.31-20-generic), Ruby 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]</p>