diff --git a/.gitignore b/.gitignore index 102c111..2a69060 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ /main /main.dwarf -/data/ +/i/ diff --git a/main.cr b/main.cr index 0b9d250..5ce1f82 100644 --- a/main.cr +++ b/main.cr @@ -5,7 +5,7 @@ require "./routes/ping" require "./routes/upload" # Create data directory if it doesn't exist -DATA_DIR="./data" +DATA_DIR="./i/" Dir.mkdir_p(DATA_DIR) # Start http server @@ -16,7 +16,10 @@ HTTP::Server.new("0.0.0.0", 8080, [ PingHandler.new, IndexHandler.new, UploadHandler.new(DATA_DIR), - # Static assetsn - HTTP::StaticFileHandler.new("./html/", directory_listing=false), - HTTP::ErrorHandler.new, + # Serve images + HTTP::StaticFileHandler.new("./i", directory_listing=false), + # Static assets + HTTP::StaticFileHandler.new("./html", directory_listing=false), + # Final error page + HTTP::ErrorHandler.new, # TODO(adam): what does this do? ]).listen diff --git a/routes/index.cr b/routes/index.cr index f3ab59e..efd7d1f 100644 --- a/routes/index.cr +++ b/routes/index.cr @@ -7,6 +7,9 @@ class IndexHandler if ctx.request.path == "/" ctx.request.path = "/index.html" end + if ctx.request.path.starts_with?("/i/") + ctx.request.path = ctx.request.path.gsub("/i/", "") + end call_next(ctx) end end diff --git a/routes/upload.cr b/routes/upload.cr index f034da4..66bd551 100644 --- a/routes/upload.cr +++ b/routes/upload.cr @@ -13,8 +13,6 @@ class UploadHandler def call(ctx) if ctx.request.method == "POST" && ctx.request.path == "/upload" - puts "#{ctx.request.method}" - # TODO(adam): Check content-length HTTP::FormData.parse(ctx.request) do |part| @@ -33,14 +31,15 @@ class UploadHandler # Generate new path checksum = hasher.hexdigest[0, 16] ext = File.extname(File.basename(part.filename || "ukn")) # TODO(adam): detect content type - path = File.join([@data_dir, "#{checksum}#{ext}"]) + name = "#{checksum}#{ext}" + path = File.join([@data_dir, name]) # Move uploaded file File.rename(file.path, path) unless File.exists?(path) # Set response - ctx.response.status_code = 200 - ctx.response.print "uploaded #{File.size(path)} bytes" + ctx.response.status_code = 302 + ctx.response.headers.add("Location", "/i/#{name}") return # quit early after successful upload end