Skip to content

Instantly share code, notes, and snippets.

@monkeydom
Last active October 9, 2015 02:27
Show Gist options
  • Save monkeydom/3424031 to your computer and use it in GitHub Desktop.
Save monkeydom/3424031 to your computer and use it in GitHub Desktop.
Start Webrick in current directory, port 9090 - added option for bonjour annoucement so it works via back to my mac!
#!/usr/bin/env ruby
require 'webrick'
require 'optparse'
include WEBrick
options = {:Port => 9090,
:DocumentRoot => './',
:Bonjour => false}
optparser=OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [options]"
opts.on("-p", "--port port_num", "Specify Port Number") do |v|
options[:Port]=v
end
opts.on("-d", "--docroot path", "Specify Document Root Folder") do |v|
options[:DocumentRoot]=v
end
opts.on("-b", "--bonjour", "Announce via Bonjour") do |v|
options[:Bonjour]=v
end
end
def registration_domains
dns_output = IO.popen('dns-sd -E') {|dns| sleep 0.5; lines_read = dns.read_nonblock(10000); %x{kill #{dns.pid}}; lines_read}
domains = []
domain_parts = nil
dns_output.split("\n").each { |line|
last_text = line.scan(/\S+$/)[0]
unless (line =~ /Added/).nil? then
domains.push(domain_parts.reverse.join('.')) unless domain_parts.nil?
domain_parts = []
end
unless domain_parts.nil? then
domain_parts.push(last_text)
end
}
domains.push(domain_parts.reverse.join('.')) unless domain_parts.nil?
return domains
end
def register_http_bonjour_service(name, port, domains = nil)
device_name = %x|hostname|.split('.')[0]
domains = registration_domains if domains.nil?
domains.each {|domain|
task_string = "dns-sd -R 'WEBRickNow - #{device_name} - #{domain}' _http._tcp. #{domain} #{port}"
puts task_string + "\n"
IO.popen(task_string)
}
end
def start_webrick(config = {})
server = HTTPServer.new(config)
yield server if block_given?
['INT', 'TERM'].each {|signal|
trap(signal) {server.shutdown}
}
server.start
end
begin
optparser.parse!(ARGV)
if (options[:Bonjour]) then
register_http_bonjour_service("WEBRickNow",options[:Port])
end
start_webrick(options)
rescue Exception=>e
puts optparser.to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment