create a http server and upload a file and return a binary response in ruby

main.rb
require 'webrick'

server = WEBrick::HTTPServer.new(Port: 8000)

server.mount_proc '/upload' do |req, res|
  file = req.query['file']
  puts "Received file: #{file}"
  
  response = WEBrick::HTTPResponse.new(req.response)
  response['Content-Type'] = 'application/octet-stream'
  response.status = 200
  response.body = File.binread(file)
  
  res.body = response.body
  res.content_type = response.content_type
  res.status = response.status
end

trap('INT') do
  server.shutdown
end

server.start
499 chars
24 lines

This code sets up a WEBrick HTTP server on port 8000. It listens for incoming requests at the /upload endpoint. When a request is received, it retrieves the uploaded file from the request parameters, reads the binary content of that file, and returns it as a binary response with the application/octet-stream content type.

The WEBrick::HTTPResponse class is used to construct the binary response with the appropriate headers and status code. Finally, the binary response is written to the response body, and the response content type and status are set appropriately.

The trap block sets up a signal handler to gracefully shut down the server if it receives an interrupt signal (e.g. when you hit Ctrl-C).

To run this code, save it to a file (e.g. server.rb) and run it with the command ruby server.rb. Then, you can upload a file to the /upload endpoint using a tool like curl:

main.rb
$ curl -X POST --data-binary "@file.png" http://localhost:8000/upload > response.png
85 chars
2 lines

This uploads a file named file.png to the server, and saves the binary response as response.png in the current directory.

gistlibby LogSnag