Last active
July 4, 2017 10:03
-
-
Save madis/6d1470c382992e463b92ee247a841587 to your computer and use it in GitHub Desktop.
Simple Webrick server
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
#!/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