create a http server with a patch route in ruby

Here's an example of how to create a basic HTTP server in Ruby using the WEBrick module that responds to PATCH requests:

main.rb
require 'webrick'

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

server.mount_proc '/patch' do |req, res|
  if req.request_method == 'PATCH'
    # handle patch request here
    res.status = 200
    res.body = 'Patch request received'
  else
    res.status = 405
    res.body = 'Method not allowed'
  end
end

trap('INT') { server.shutdown }

server.start
355 chars
19 lines

This creates a server listening on port 8000 that will respond to PATCH requests to the /patch endpoint. The implementation of the PATCH request would go in the block provided to mount_proc. In this example, it simply returns a response of 'Patch request received' with a 200 status code when a PATCH request is received. Otherwise, a 405 status code is returned.

related categories

gistlibby LogSnag