To create a HTTP server that parses cookies and returns a JSON response in Ruby, we can use the following code:
main.rb562 chars26 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