/server.rb Secret
Created
July 28, 2019 13:31
A little server example extracted from un.rb for barg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: false | |
# | |
# = un.rb | |
# | |
# Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org> | |
# | |
# This program is free software. | |
# You can distribute/modify this program under the same terms of Ruby. | |
# | |
# ruby -run -e httpd -- [OPTION] DocumentRoot | |
require 'fileutils' | |
require 'optparse' | |
def setup(options = "", *long_options) | |
caller = caller_locations(1, 1)[0].label | |
opt_hash = {} | |
argv = [] | |
OptionParser.new do |o| | |
options.scan(/.:?/) do |s| | |
opt_name = s.delete(":").intern | |
o.on("-" + s.tr(":", " ")) do |val| | |
opt_hash[opt_name] = val | |
end | |
end | |
long_options.each do |s| | |
opt_name, arg_name = s.split(/(?=[\s=])/, 2) | |
opt_name.delete_prefix!('--') | |
s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}" | |
puts "#{opt_name}=>#{s}" if $DEBUG | |
opt_name = opt_name.intern | |
o.on(s) do |val| | |
opt_hash[opt_name] = val | |
end | |
end | |
o.on("-v") do opt_hash[:verbose] = true end | |
o.on("--help") do | |
UN.help([caller]) | |
exit | |
end | |
o.order!(ARGV) do |x| | |
if /[*?\[{]/ =~ x | |
argv.concat(Dir[x]) | |
else | |
argv << x | |
end | |
end | |
end | |
yield argv, opt_hash | |
end | |
setup("", "BindAddress=ADDR", "Port=PORT", "MaxClients=NUM", "TempDir=DIR", | |
"DoNotReverseLookup", "RequestTimeout=SECOND", "HTTPVersion=VERSION", | |
"ServerName=NAME", "ServerSoftware=NAME", | |
"SSLCertificate=CERT", "SSLPrivateKey=KEY") do | |
|argv, options| | |
require 'webrick' | |
opt = options[:RequestTimeout] and options[:RequestTimeout] = opt.to_i | |
[:Port, :MaxClients].each do |name| | |
opt = options[name] and (options[name] = Integer(opt)) rescue nil | |
end | |
if cert = options[:SSLCertificate] | |
key = options[:SSLPrivateKey] or | |
raise "--ssl-private-key option must also be given" | |
require 'webrick/https' | |
options[:SSLEnable] = true | |
options[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(cert)) | |
options[:SSLPrivateKey] = OpenSSL::PKey.read(File.read(key)) | |
options[:Port] ||= 8443 # HTTPS Alternate | |
end | |
options[:Port] ||= 8080 # HTTP Alternate | |
options[:DocumentRoot] = argv.shift || '.' | |
s = WEBrick::HTTPServer.new(options) | |
shut = proc {s.shutdown} | |
siglist = %w"TERM QUIT" | |
siglist.concat(%w"HUP INT") if STDIN.tty? | |
siglist &= Signal.list.keys | |
siglist.each do |sig| | |
Signal.trap(sig, shut) | |
end | |
s.start | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment