DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Basic WEBrick Setup For Local Web Server

06.17.2008
| 18421 views |
  • submit to reddit
        Put the following functions and aliases into your ~/.bash_login (or alternatives).


unset -f webrick_local

function webrick_local() { 

   declare root_dir="${HOME}/Desktop/www"

   /bin/mkdir -p "${root_dir}/WEBrickLog"
   /bin/chmod 0754 "${root_dir}" "${root_dir}/WEBrickLog"

   /usr/bin/touch "${root_dir}/WEBrickLog/webrick.pid" "${root_dir}/WEBrickLog/webrick_ruby.pid"
   /bin/chmod 0644 "${root_dir}/WEBrickLog/webrick.pid" "${root_dir}/WEBrickLog/webrick_ruby.pid"

#   /usr/bin/touch "${root_dir}/index.html"
#   /bin/chmod 0754 "${root_dir}/index.html"


/usr/local/bin/ruby <<-HEREDOC

   require 'webrick'
   require 'webrick/accesslog'
   include WEBrick

   require 'thread'
   require 'pp'

   root_dir = "${root_dir}"
   http_dir = File.expand_path(root_dir)

   File.open(http_dir + "/WEBrickLog/webrick_ruby.pid", "w") do |f|
      f.puts(Process.pid)
   end

   # cf. http://microjet.ath.cx/webrickguide/html/Logging.html
   webrick_log_file = File.expand_path(http_dir + "/WEBrickLog/webrick.log")
   #webrick_log_file = '/dev/null'  # disable logging
   webrick_logger = WEBrick::Log.new(webrick_log_file, WEBrick::Log::DEBUG)

   access_log_stream = webrick_logger
   access_log = [[ access_log_stream, WEBrick::AccessLog::COMBINED_LOG_FORMAT ]]

   system_mime_table = WEBrick::HTTPUtils::load_mime_types('/private/etc/httpd/mime.types.default')
   system_mime_table.store('rhtml', 'text/html')   # add a mime type for .rhtml files
   system_mime_table.store('php', 'text/html')
   system_mime_table.store('rb', 'text/plain')
   system_mime_table.store('pid', 'text/plain')
   #pp system_mime_table.sort_by { |k,v| k }

   server = WEBrick::HTTPServer.new(
     :BindAddress     =>    "localhost",
     :Port            =>    9090,
     :DocumentRoot    =>    http_dir,
     :FancyIndexing   =>    true,
     :MimeTypes       =>    system_mime_table,
     :Logger          =>    webrick_logger,
     :AccessLog       =>    access_log
   )

   server.config.store(:DirectoryIndex, server.config[:DirectoryIndex] << "default.htm")
   #pp server.config

   # cf. http://snippets.dzone.com/posts/show/5208
   class TimeServlet < HTTPServlet::AbstractServlet

      def do_GET(req, res)
         res['Content-Type'] = 'text/html'
         res.status = 200
         res.body = "<html>Time: #{Time.now.to_s}</html>" + "\n"
      end

      # cf. http://www.hiveminds.co.uk/node/244, published under the
      # GNU Free Documentation License, http://www.gnu.org/copyleft/fdl.html

      @@instance = nil
      @@instance_creation_mutex = Mutex.new

      def self.get_instance(config, *options)
         #pp @@instance
         @@instance_creation_mutex.synchronize { 
            @@instance = @@instance || self.new(config, *options) }
      end

   end


   # cf. http://ttripp.blogspot.com/2007/01/fun-with-http.html
   class PostDumper < WEBrick::HTTPServlet::AbstractServlet
  
      # Reload file for each request, instantly
      # updating the server with code changes 
      # without needing a restart.

=begin
      def PostDumper.get_instance( config, *options )
         load __FILE__
         PostDumper.new config, *options
      end
=end

      # cf. http://www.hiveminds.co.uk/node/244, published under the
      # GNU Free Documentation License, http://www.gnu.org/copyleft/fdl.html

      @@instance = nil
      @@instance_creation_mutex = Mutex.new

      def self.get_instance(config, *options)
         #pp @@instance
         @@instance_creation_mutex.synchronize { 
            @@instance = @@instance || self.new(config, *options) }
      end

      def do_GET( request, response )
         response.status = 200
         response['Content-Type'] = "text/plain"
         response.body = dump_request( request )
      end
  
      def do_POST( request, response )
         response.status = 200
         response['Content-Type'] = "text/plain"
         response.body = dump_request( request )
         response.body << request.body
      end
  
      def dump_request( request )
         request.request_line << "\r\n" <<
         request.raw_header.join( "" ) << "\r\n"
      end
   end

   server.mount("/dump", PostDumper)
   server.mount("/time", TimeServlet, {:FancyIndexing=>true})

   # handle signals
   %w(INT).each do |signal|
      trap(signal) { server.shutdown }
   end

   server.start

HEREDOC

return 0

}

export -f webrick_local

# start WEBrick alias
alias webrick='swr'

# start WEBrick
unset -f swr
function swr() {   
  declare webrick_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick.pid"
  if [[ -e "${webrick_pid_file}" ]]; then echo "WEBrick already started!"; return 1; fi
  /bin/bash -c "webrick_local" &
  declare WEBRICKPID=$!
  mkdir -p "${HOME}/Desktop/www/WEBrickLog"
  echo $WEBRICKPID > "${HOME}/Desktop/www/WEBrickLog/webrick.pid"
  return 0
}
export -f swr

# quit WEBrick
unset -f qwr
function qwr() { 
   declare webrick_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick.pid"
   declare webrick_ruby_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick_ruby.pid"
   if [[ ! -e "${webrick_pid_file}" ]]; then echo "no such file: ${webrick_pid_file}"; return 1; fi
   declare PIDW=$(cat "${webrick_pid_file}" 2>/dev/null)
   declare PIDR=$(cat "${webrick_ruby_pid_file}" 2>/dev/null)
   kill -INT $PIDW 2>/dev/null || echo "no such PIDW: ${PIDW}"
   kill -INT $PIDR 2>/dev/null || echo "no such PIDR: ${PIDR}"
   rm -f "${webrick_pid_file}" "${webrick_ruby_pid_file}"
   return 0
}
export -f qwr

# quit WEBrick; cf. Job Control Commands, http://tldp.org/LDP/abs/html/x8816.html
###alias qwr='echo "quit WEBrick with ctrl-c ..."; fg %webrick 2>/dev/null'

alias openwww='/usr/bin/open http://localhost:9090'
alias wrlog='/usr/bin/open http://localhost:9090/WEBrickLog/webrick.log'


#----------------------------------------


source ~/.bash_login

webrick

openwww
wrlog
open http://localhost:9090 
open http://localhost:9090/WEBrickLog
open http://localhost:9090/WEBrickLog/webrick.log

open http://localhost:9090/time
open http://localhost:9090/dump

wrlog
qwr

Further information:

- <a href="http://www.webrick.org">WEBrick</a>
- <a href="http://www.ruby-doc.org/stdlib/libdoc/webrick/rdoc/index.html">WEBrick RDoc</a>
- <a href="http://www.hiveminds.co.uk/node/245">What is WEBrick?</a>
- <a href="http://www.hiveminds.co.uk/node/244">Guide to using WEBrick for Rails development</a>
- <a href="http://www.igvita.com/2007/02/13/building-dynamic-webrick-servers-in-ruby/">Dynamic WEBrick Servers in Ruby</a>
- <a href="http://microjet.ath.cx/WebWiki/WEBrick.html">Gnome's Guide to WEBrick</a>
- <a href="http://codeidol.com/other/rubyckbk/Internet-Services/Running-Servlets-with-WEBrick/">Running Servlets with WEBrick</a>
- <a href="http://ruby.jamisbuck.org/rsphandler.rb">rsphandler</a>
- <a href="http://eigenclass.org/hiki/webrick-rewrite-rules">URL rewriting with WEBrick</a>