Skip to content

Commit

Permalink
Add uploader
Browse files Browse the repository at this point in the history
  • Loading branch information
kou committed May 19, 2014
1 parent 31d6ae0 commit 1b7fce4
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
/public/
1 change: 1 addition & 0 deletions Gemfile
@@ -1,3 +1,4 @@
source "https://rubygems.org/"

gem "rake"
gem "puma"
6 changes: 5 additions & 1 deletion Gemfile.lock
@@ -1,10 +1,14 @@
GEM
remote: https://rubygems.org/
specs:
rake (10.3.1)
puma (2.8.2)
rack (>= 1.1, < 2.0)
rack (1.5.2)
rake (10.3.2)

PLATFORMS
ruby

DEPENDENCIES
puma
rake
2 changes: 1 addition & 1 deletion Procfile
@@ -1 +1 @@
web: bundle exec ruby -run -e httpd -- --port=$PORT --do-not-reverse-lookup .
web: bundle exec puma --port $PORT config.ru
81 changes: 81 additions & 0 deletions config.ru
@@ -0,0 +1,81 @@
# -*- ruby -*-

require "fileutils"

class Uploader
class ValidationError < StandardError
end

def initialize(request, response)
@request = request
@response = response
@response["Content-Type"] = "text/plain"
end

def run
begin
validate
rescue ValidationError
else
upload
end

@response.finish
end

private
def validate
validate_method
validate_path
validate_content
end

def validation_error(message)
@response.status = 400
@response.write(message)
raise ValidationError
end

def validate_method
return if @request.put?
validation_error("must be PUT\n")
end

def validate_path
return unless @request.path.end_with?("/")
validation_error("must be file name\n")
end

def validate_content
return if @request.body
validation_error("body is required\n")
end

def upload
path = "public#{@request.path}"
FileUtils.mkdir_p(File.dirname(path))
File.open(path, "wb") do |output|
buffer_size = 8912
buffer = ""
while @request.body.read(buffer_size, buffer)
output.write(buffer)
end
end

@response.write("Uploaded\n")
end
end

file_server = Rack::File.new("public")

application = lambda do |env|
request = Rack::Request.new(env)
response = Rack::Response.new
if request.get?
file_server.call(env)
else
uploader = Uploader.new(request, response)
uploader.run
end
end
run application

0 comments on commit 1b7fce4

Please sign in to comment.