Ruby Web Server with SSI

For a class I had to write a threaded webserver that would insert a banner at the top of each page (bonus if it was randomly selected) and some dynamic content at the bottom. I chose to do it in Ruby, and was rewarded with about 100 lines less of code than the Java version. See the Java version starting point other students used here: http://fragments.turtlemeat.com/javawebserver.php. It could be a little cleaner, but it’s not too bad.

This page is OLD and probably contains errors, out of date information, security flaws or other problems. I am keeping it around because it might be helpful to someone.

#!/usr/bin/env ruby
    # Michael Moore, IT 210, November 2006,
    # Simple web server that does SSI and random banner rotation

    require 'webrick' # require needed libraries (included in ruby)

    $docroot = "j://rws/docs/"  # Set document root as a global variable
    server = WEBrick::HTTPServer.new(:Port => 8888,:DocumentRoot => $docroot)  # new HTTP server on localhost:8888

    class SuperServlet  < WEBrick::HTTPServlet::AbstractServlet # override default HTTP GET handler
	def do_GET(req, res)  # req == HTTP request object, res == HTTP response object

	filename = req.meta_vars["PATH_INFO"].gsub(req.meta_vars["QUERY_STRING"],"") # Get just the requested filename

	    if filename.downcase.slice(filename.length - 4,4).slice('html') # if it ends in html, return a modded version
		# Read file into a single string, do some search and replaces (gsub) add a random banner (0.JPG--4.JPG) and return it to the requester
		res.body = IO.readlines($docroot + filename).join.gsub("<body>","<body><img src='/#{rand(5)}.JPG'><br>").gsub("</body>","<br>#{Time.now.to_s}</body>")
	    else # It wasn't an HTML page, so just return the requested file
		res['content-length'] = File::stat($docroot + filename).size # without this, the browser doesn't know when to quit?
		res.body = open($docroot + filename, "rb") # return the file contents
	    end
	end
    end
    server.mount("/", SuperServlet)  # Use our custom override on anything above this point (ie. all dirs)
    trap("INT"){server.shutdown}     # Catch ctrl-c to do a clean shutdown
    server.starting # Start the server!

This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *