summaryrefslogtreecommitdiff
path: root/lib/gitem/server.rb
blob: 82edc9035ce622fcdb6403a1e373ff8f4ee3671a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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