create a http server with a specific route and a specific status code in ruby

To create an HTTP server with a specific route and a specific status code in Ruby, you can use the built-in WEBrick library.

Here's an example code snippet that sets up a simple HTTP server with a single route that returns a 200 OK status code:

main.rb
require 'webrick'

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

server.mount_proc '/' do |req, res|
  res.status = 200
  res.body = 'Hello, world!'
end

trap('INT') { server.shutdown }

server.start
200 chars
13 lines

In this example, we use the WEBrick::HTTPServer class to create a new server instance, then call the mount_proc method to define a route for the root path ("/"). The block passed to mount_proc is called for each request that matches the route, and sets the response status code to 200 and the response body to "Hello, world!".

Finally, we use the trap method to catch the INT signal (which is generated when the user presses Ctrl-C), and call server.shutdown to gracefully shut down the server. Finally, we call server.start to begin listening for incoming requests on port 8000.

You can modify this example to define additional routes and response status codes as needed.

gistlibby LogSnag