return a json response from a http server in ruby

To return a JSON response from an HTTP server in Ruby, you can use the built-in json library and the rack middleware. Here's an example:

main.rb
require 'json'
require 'rack'

app = Proc.new do |env|
  # Create the JSON response
  data = { message: 'Hello, world!' }
  json_resp = JSON.generate(data)

  # Return the response
  [200, { 'Content-Type' => 'application/json' }, [json_resp]]
end

# Start the server
Rack::Handler::WEBrick.run app, Port: 3000
311 chars
15 lines

In this example, we create a simple Proc that generates a JSON response with a message "Hello, world!". We set the Content-Type header to application/json to indicate that the response is JSON.

Then, we use the rack middleware to start an HTTP server and pass in our Proc as the application. We use the WEBrick server implementation and set the server port to 3000.

When you run this script and navigate to http://localhost:3000 in your web browser, you should see a JSON response with the message "Hello, world!".

related categories

gistlibby LogSnag