commit fcd814ccf6bc575787f3f42c5bb07c69d3a23354 Author: sandyx Date: Tue Oct 14 06:34:26 2025 -0500 first diff --git a/index.html b/index.html new file mode 100644 index 0000000..5c6d819 --- /dev/null +++ b/index.html @@ -0,0 +1,11 @@ + + + + + + + +Apocrypha +

hello world

+ + \ No newline at end of file diff --git a/main.rb b/main.rb new file mode 100644 index 0000000..4b7abba --- /dev/null +++ b/main.rb @@ -0,0 +1,102 @@ +#!/usr/bin/ruby + +# main.rb + +require 'socket' +require 'fileutils' +require 'pathname' + +Root = '.' +Port = 8080 + +class HttpResponse + def self.content_length(resp) + "Content-Length: #{resp.length}" + end + + def self.content_type(resp) + ctype = { + ".png" => "image/png", + ".txt" => "text/plain", + ".html" => "text/html", + ".css" => "text/css", + ".mp3" => "audio/mpeg", + ".ttf" => "font/ttf", + ".mp4" => "video/mp4", + ".pdf" => "application/pdf" + } + + "Content-Type: #{ctype[resp.ext]}" + end + + def self.build(resp) + resp.route + + if resp.not_found? + return "HTTP/1.1 404 NOT FOUND\r\n" + end + + headers = [content_length(resp), content_type(resp)].join("\r\n") + puts headers + + return "HTTP/1.1 200 OK\r\n#{headers}\r\n#{resp.data}" + end +end + +class HttpRouter + attr_reader :ext + attr_reader :length + attr_reader :data + + def initialize(path) + @path = Pathname.new(path) + @ext = File.extname(path) + @not_found = false + @data + end + + def route + case @path + when "/" + @path = "./index.html" + return route + else + if File.exist? @path.basename + @data = File.read(Root + @path.to_s) + @length = @data.length + @ext = File.extname(@path) + else + @not_found = true + end + end + end + + def not_found? + @not_found + end +end + +class HttpServer + def initialize(port) + @server = TCPServer.new port + end + + def accept_connection + while session = @server.accept + request = session.gets + + verb, path, protocol = request.split(' ') unless request.nil? + if protocol === 'HTTP/1.1' + resp = HttpRouter.new(path) + session.print HttpResponse.build(resp) + else + session.print 'Connection Refused' + end + + session.close + end + end +end + +server = HttpServer.new Port +server.accept_connection \ No newline at end of file