Skip to content

Instantly share code, notes, and snippets.

@danielgracia
Last active March 13, 2017 23:34
Show Gist options
  • Save danielgracia/ef2a2e12efb015b252df to your computer and use it in GitHub Desktop.
Save danielgracia/ef2a2e12efb015b252df to your computer and use it in GitHub Desktop.
CGI Server in Ruby
#!/usr/bin/env ruby
# Script depends on whatever WEBrick has in Ruby 2.2.3
# Includes for convenience
require 'webrick'
include WEBrick
# Initialize plain server, no indexing, else CGI handling will be broken
s = HTTPServer.new(
:Port => 3000
)
# Set CGI handler for every executable file in this directory, recursively
# (Security shmurity)
Dir.glob("**/*") do |file|
if File.executable_real?(file) and not File.directory?(file)
puts "/#{file}" => File.expand_path(file)
s.mount("/#{file}", HTTPServlet::CGIHandler, File.expand_path(file))
end
end
# Set enviroment variable because we can
ENV['ENVIRONMENT'] = 'development'
# Now we can mount FileHandler later for pretty indexes
s.mount("/", HTTPServlet::FileHandler, Dir.pwd, FancyIndexing: true)
# Trap INT signal so we won't be trapped FOREVER
trap("INT") { s.shutdown }
# Drink coffee
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment