Class: Pbin::PBServerlet

Inherits:
WEBrick::HTTPServlet::AbstractServlet
  • Object
show all
Defined in:
lib/pbin/pb_servlet.rb

Instance Method Summary collapse

Instance Method Details

#do_GET(request, response) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/pbin/pb_servlet.rb', line 7

def do_GET(request, response)
  dirname = request.path.split('/').last
  dirpath = "#{STORENAME}/#{dirname}"

  # If the paste file is not found then return 404 with empty response
  begin
    content = File.read("#{dirpath}/index.txt")
    response.status = 200
    response.body = content
  rescue Errno::ENOENT
    response.status = 404
    response.body = ""
  end
end

#do_POST(request, response) ⇒ Object



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
47
48
49
50
51
52
53
54
# File 'lib/pbin/pb_servlet.rb', line 22

def do_POST(request, response)
  content = request.query["p"]
  # Try to memoize this
  slug_size = 4
  dirname = nil
  # file_name = Digest::SHA1.hexdigest(content)[0..5]
  loop do
    dirname = Slug.generate(slug_size)
    if File.exists?("#{STORENAME}/#{dirname}")
      if slug_size > 10
        response.status = 422
        response['Content-Type'] = 'text/plain'
        response.body = "Failed to create"
        break
      end
      slug_size += 1
    else
      break
    end
  end

  dirpath = "#{STORENAME}/#{dirname}"

  Dir.mkdir(dirpath)

  f = File.open("#{dirpath}/index.txt", "wb")
  f.write(content)
  f.close

  response.status = 200
  response['Content-Type'] = 'text/plain'
  response.body = dirname
end