# frozen_string_literal: true module Gitem class Server attr_reader :url def initialize(root, port = 8000) @root = root @port = port @url = "http://localhost:#{port}" end def start puts "🌐 Server running at #{@url}" puts " Press Ctrl+C to stop\n\n" server = WEBrick::HTTPServer.new( Port: @port, Logger: WEBrick::Log.new($stderr, WEBrick::Log::WARN), AccessLog: [] ) server.mount_proc '/' do |req, res| path = File.join(@root, req.path) path = File.join(path, 'index.html') if File.directory?(path) if File.exist?(path) && !File.directory?(path) res.body = File.read(path) res.content_type = WEBrick::HTTPUtils.mime_type(path, WEBrick::HTTPUtils::DefaultMimeTypes) else index_path = File.join(@root, 'index.html') if File.exist?(index_path) res.body = File.read(index_path) res.content_type = 'text/html' else res.status = 404 res.body = 'Not Found' end end end trap("INT") { server.shutdown } trap("TERM") { server.shutdown } server.start end end end