#!/usr/bin/env ruby require 'rubygems' require 'serverside' require 'optparse' $cmd_config = { :host => '0.0.0.0', :ports => 8000..8000 } opts = OptionParser.new do |opts| opts.banner = "Usage: serverside start|stop|restart|serve [app_file]" opts.define_head "ServerSide, a fast and simple web framework for ruby." opts.separator "" opts.separator "The supplied application path can be directory or file references. \ If the path refers to a directory the system will try to load serverside.rb in \ that directory. If no path is given, the current working directory is assumed." opts.separator "" opts.separator "* The start, stop and restart commands are used to control the daemon." opts.separator "* The serve command is used to start the server without forking." opts.separator "" opts.separator "Options:" opts.on("-h", "--host HOSTNAME", "Host to bind to (default is all IPs)") do |v| $cmd_config[:host] = v end opts.on("-p", "--port NUM", "Port or port range (default is 8000)") do |v| $cmd_config[:ports] = (v =~ /\.\./) ? eval(v) : v.to_i..v.to_i end # No argument, shows at tail. This will print an options summary. # Try it and see! opts.on_tail("-?", "--help", "Show this message") do puts opts exit end # Another typical switch to print the version. opts.on_tail("-v", "--version", "Show version") do class << Gem; attr_accessor :loaded_specs; end specs = Gem.loaded_specs['serverside'] puts "ServerSide #{specs.version} (#{specs.date.strftime '%Y-%m-%d'})" exit end end opts.parse! ARGV if ARGV.length < 1 puts opts exit end $cmd = ARGV.shift unless %w(start stop restart serve).include?($cmd) puts "Invalid command specified. Known commands are: start, stop, restart, serve." exit end $path = ARGV.shift || '.' if File.file?($path) app_code = IO.read($path) elsif File.file?($path/'serverside.rb') app_code = IO.read($path/'serverside.rb') end ServerSide::HTTP::Static.static_root = File.expand_path($path) $server = ServerSide::HTTP::Server.new do if app_code module_eval(app_code) else def handle(req) ServerSide::HTTP::Response.static(req.path) end end end if $cmd == 'serve' if $cmd_config[:ports].begin != $cmd_config[:ports].end puts "Please specify a single port." exit end puts "Serving at #{$cmd_config[:host]}:#{$cmd_config[:ports].begin}..." trap('INT') {exit} $server.start($cmd_config[:host], $cmd_config[:ports].begin) else daemon_class = Class.new(Daemon::Cluster) do meta_def(:pid_fn) {Daemon::WorkingDirectory/'serverside.pid'} meta_def(:server_loop) do |port| $server.start($cmd_config[:host], port) end meta_def(:ports) {$cmd_config[:ports]} end Daemon.control(daemon_class, $cmd) end