File: webserve.rb

Project: Invitation to Ruby

#!/usr/bin/env ruby

require 'socket'

def show_header(out, type)
  out.print "HTTP/1.1 200/OK\r\nContent-type: #{type}\r\n\r\n"
end

def show_error(out)
  out.print "HTTP/1.1 404/URL Missing\r\n\r\n"
end

def copyfile(filename, out)
  open (filename) { |file|
    while line = file.gets
      out.print line
    end
  }
end

port = (ARGV[0] || 8888).to_i
server = TCPServer.new('localhost', port)
while (session = server.accept)
  command, path, protocol = session.gets.split
  filename = "." + path
  if command == 'GET'
    begin
      case path
      when '/time'
	puts "Doing Time"
	show_header(session, 'text/html')
	session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
      when /.*\.html?$/
	puts "Sending HTML File: [#{filename}]"
	show_header(session, 'text/html')
	copyfile(filename, session)
      else
	puts "Sending Text File: [#{filename}]"
	show_header(session, 'text/plain')
	copyfile(filename, session)
      end
    rescue
      session.print "File #{filename} Not Found\r\n"
    end
  end
  session.close
end


[ Index ][ Table of Contents ]
Generated by [ source2html ]