Skip to content

Instantly share code, notes, and snippets.

@lillesvin
Created September 16, 2020 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lillesvin/9bbae5d4b0103154a33713a729442623 to your computer and use it in GitHub Desktop.
Save lillesvin/9bbae5d4b0103154a33713a729442623 to your computer and use it in GitHub Desktop.
Simple Ruby/WEBrick wrapper to serve stuff over HTTPS/TLS/SSL
#!/usr/bin/ruby
require 'webrick/https'
require 'openssl'
require 'optparse'
# Defaults
cfg = {
port: 8443,
root: "."
}
# Command line options
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on("-l", "--letsencrypt DIR", "Use Let's Encrypt certificate and private key from DIR") do |l|
cfg[:letsencrypt] = l
end
opts.on("-c", "--cert FILE", "Use cert from FILE") do |c|
cfg[:cert] = c
end
opts.on("-k", "--key FILE", "Use private key from FILE") do |k|
cfg[:key] = k
end
opts.on("-p", "--port INT", "Listen on port INT (default: 8443)") do |p|
cfg[:port] = p
end
opts.on("-r", "--root DIR", "Use DIR as document root (default: ./)") do |r|
cfg[:root] = r
end
opts.on("-h", "--help", "Show this help and exit") do
puts opts
exit
end
end.parse!
# Let's Encrypt Magic
if !cfg[:letsencrypt].nil? && Dir.exist?(cfg[:letsencrypt])
cfg[:cert] = File.join(cfg[:letsencrypt], "cert.pem")
cfg[:key] = File.join(cfg[:letsencrypt], "privkey.pem")
end
# The actual stuff
WEBrick::HTTPServer.new(
Port: cfg[:port],
DocumentRoot: cfg[:root],
SSLEnable: true,
SSLCertificate: OpenSSL::X509::Certificate.new(File.open(cfg[:cert]).read),
SSLPrivateKey: OpenSSL::PKey::RSA.new(File.open(cfg[:key]).read)
).start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment