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

main.rb
require 'webrick'
require 'json'

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

server.mount_proc '/' do |req, res|
  if req.request_method == 'POST'
    req_body = JSON.parse(req.body)
    res.body = "Received JSON: #{req_body}"
  else
    res.body = 'Hello World'
  end
end

trap('INT') { server.shutdown }

server.start
323 chars
18 lines

This creates a HTTP server listening on port 8000. When a POST request is sent to '/', the server reads the request body as JSON and outputs a message with the received JSON. For any other request method or path, it responds with 'Hello World'.

related categories

gistlibby LogSnag