Class: UgotServer

Inherits:
Object
  • Object
show all
Defined in:
lib/ugotserver.rb

Instance Method Summary collapse

Constructor Details

#initialize(port = 1870) ⇒ UgotServer

Returns a new instance of UgotServer.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/ugotserver.rb', line 5

def initialize(port = 1870)
  @WEB_ROOT = File.expand_path "../../..", __FILE__
  @server = TCPServer.new('localhost',port)

  @CONTENT_TYPE_MAPPING = {
    'html' => 'text/html',
    'txt' => 'text/plain',
    'png' => 'image/png',
    'jpg' => 'image/jpeg'
  }

  @DEFAULT_CONTENT_TYPE = 'application/octet-stream'
  loop_it
end

Instance Method Details

#content_type(path) ⇒ Object



20
21
22
23
# File 'lib/ugotserver.rb', line 20

def content_type(path)
  ext = File.extname(path).split(".").last
  @CONTENT_TYPE_MAPPING.fetch(ext, @DEFAULT_CONTENT_TYPE)
end

#loop_itObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/ugotserver.rb', line 40

def loop_it
  loop do
    socket = @server.accept
    request_line = socket.gets

    STDERR.puts request_line

    path = requested_file(request_line)

    path = File.join(path, 'index.html') if File.directory?(path)

    if File.exist?(path) && !File.directory?(path)
      File.open(path, 'rb') do |file|
        socket.print "HTTP/1.1 200 OK\r\n" +
                  "Content-Type: #{content_type(file)}\r\n" +
                  "Content-Length: #{file.size}\r\n" +
                  "Connection: close\r\n"

        socket.print "\r\n"

        IO.copy_stream(file, socket)
      end
    else
      message = "File Not Found\n"

      socket.print "HTTP/1.1 404 Not Found\r\n" +
                  "Content-Type: text/plain\r\n" +
                  "Content-Length: #{message.size}\r\n" +
                  "Connection: close\r\n"

      socket.print "\r\n"

      socket.print message
    end

    socket.close
  end
end

#requested_file(request_line) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/ugotserver.rb', line 25

def requested_file(request_line)
  request_uri = request_line.split(" ")[1]
  path = URI.unescape(URI(request_uri).path)
  clean = []

  parts = path.split("/")

  parts.each do |part|
    next if part.empty? || part == '.'
    part == '..' ? clean.pop : clean << part
  end

  File.join(@WEB_ROOT, *clean)
end