create a http server and read the request body as binary in ruby

To create a simple HTTP server in Ruby, we can use the built-in WEBrick library. The following code initializes a server at http://localhost:8000 and prints the request body as binary:

main.rb
require 'webrick'

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

server.mount_proc('/') do |req, res|
  puts req.body.b # 'b' returns the binary data
end

server.start
168 chars
10 lines

When a request is made to the server, the block passed to server.mount_proc is executed. The req parameter contains all the details of the incoming request, including the request body. By calling req.body.b, we get the binary data as a string of bytes.

Note that in production, it's recommended to use a dedicated web server like Apache or Nginx to handle incoming HTTP requests to avoid security vulnerabilities.

gistlibby LogSnag