From: Phlip Date: 2002-10-29T14:10:49+09:00 Subject: Snippet: Tiny Featureless Ruby Web Server Rubies: This would have taken me less than a wall-clock hour if I didn't have a life: #!/usr/bin/ruby # a web server in Ruby require 'socket' $mimeTypes = { 'jpg' => 'image/jgp', 'gif' => 'image/gif', 'png' => 'image/png', 'html' => 'text/html', 'pdf' => 'application/pdf' } $response = {} # TODO make me a map... $response[200] =\ '''HTTP/1.0 200 Okay Server: ws30 Content-type: %s %s ''' $response[301] =\ """HTTP/1.0 301 Moved Server: ws30 Content-type: text/plain Location: %s moved%s """ $response[404] =\ '''HTTP/1.0 404 Not Found Server: ws30 Content-type: text/plain %s not found%s ''' def serverSocket host, port # TODO make these real arguments... s = TCPServer.new('localhost', port) return s end def listen s connection, client = s.accept() return connection end def getRequest stream method = nil while 1 do line = stream.readline() if line.strip().length() == 0 then break elsif ! method method, uri, protocol = line.split() end end return uri end def listDirectory uri return 'directory none of your business' end def getFile path f = open( path ) return f.read() # TODO begin/rescue here end def getContent uri print 'fetching:', uri begin path = '.' + uri if File.file?( path ) then return [ 200, getMime( uri ), getFile( path ) ] end if File.directory?( path ) then if( uri[uri.length() - 1].chr == '/' ) then return [ 200, 'text/html', listDirectory( uri ) ] else return [ 301, uri + '/' ] end else return [ 404, uri ] end # TODO actually stringify the error ;-) rescue return [ 404, 'some dumb IO error' ] end end def getMime uri type = $mimeTypes[ uri.split('.')[-1]] type = 'text/plain' if type == nil return type end def sendResponse stream, content $responseType = $response[content[0]] content.push("") response = sprintf($responseType, content[1], content[2] ) stream.write( response ) end if __FILE__ == $0 then server = serverSocket( 'localhost', 8080 ) begin while 1 do stream = listen ( server ) sendResponse( stream, getContent( getRequest( stream ) ) ) stream.close() end rescue print 'shutting down...' end server.close() end -- Phlip http://flea.sourceforge.net -- Got in trouble at StarBucks. I tried to order "A double latte mocha and a body piercing." --