Skip to content

Instantly share code, notes, and snippets.

@madis
Last active July 4, 2017 10:03
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 madis/6d1470c382992e463b92ee247a841587 to your computer and use it in GitHub Desktop.
Save madis/6d1470c382992e463b92ee247a841587 to your computer and use it in GitHub Desktop.
Simple Webrick server
#!/usr/bin/env ruby
require 'webrick'
class Servlet < WEBrick::HTTPServlet::FileHandler
PORT = 4200
INDEX_FILE = 'index.html'
ROOT_PATH = File.expand_path(__dir__) # Folder of current file
def do_GET(request, response)
if readable_file_exists?(request.path)
super(request, response) # Default handling with correct content types
else
response.content_type = 'text/html'
response.body = File.read(full_path(INDEX_FILE))
end
end
private
def readable_file_exists?(path)
File.readable?(full_path(path)) && File.file?(full_path(path))
end
def full_path(path)
File.join(ROOT_PATH, path)
end
end
server = WEBrick::HTTPServer.new(Port: Servlet::PORT)
server.mount '/', Servlet, Servlet::ROOT_PATH
trap("INT") { server.shutdown }
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment