create a http server and parse cookies and return a json response in ruby

To create a HTTP server that parses cookies and returns a JSON response in Ruby, we can use the following code:

main.rb
require 'json'
require 'webrick'

server = WEBrick::HTTPServer.new :Port => 8000

server.mount_proc '/' do |req, res|
  
  # Parse cookies from the request
  req_cookies = WEBrick::Cookie.parse(req.header['cookie'])
  
  # Create a response hash
  response = {
    message: 'Hello World!',
    cookies_received: req_cookies.length
  }
  
  # Set the response headers
  res['Content-Type'] = 'application/json'
  res['Set-Cookie'] = WEBrick::Cookie.new('my_cookie', 'my_value').to_s
  
  # Send the response
  res.body = JSON.generate(response)
end

server.start
562 chars
26 lines

In this code, we first require the json and webrick libraries. json is used to generate JSON responses, while webrick is used to create the HTTP server.

We then create a new WEBrick::HTTPServer instance on port 8000. We define a route for the root (/) of the server using server.mount_proc. This route takes a request (req) and response (res) object.

We parse the cookies from the request header using WEBrick::Cookie.parse, and create a response hash with a "message" key and a "cookies_received" key.

We set the response headers using res['Content-Type'] and res['Set-Cookie']. The Set-Cookie header sets a cookie with the name "my_cookie" and value "my_value".

We then generate a JSON response using JSON.generate and set it as the response body using res.body.

Finally, we start the server using server.start.

Note that this is a very basic example, and in practice you would likely want to handle errors, use middleware, and parse the request body as well.

gistlibby LogSnag