Http Client in Ruby

Here’s an idiomatic Ruby example demonstrating the concept of an HTTP client, similar to the Go example provided:

require 'net/http'
require 'uri'

def main
  # Issue an HTTP GET request to a server
  uri = URI('https://www.example.com')
  response = Net::HTTP.get_response(uri)

  # Print the HTTP response status
  puts "Response status: #{response.code} #{response.message}"

  # Print the first 5 lines of the response body
  response.body.lines.take(5).each do |line|
    puts line.chomp
  end
rescue SocketError => e
  puts "Error: #{e.message}"
end

main

This Ruby script demonstrates how to create a simple HTTP client using the standard library. Let’s break it down:

  1. We start by requiring the necessary libraries: net/http for HTTP functionality and uri for URI parsing.

  2. We define a main method to encapsulate our code, following a common Ruby practice for scripts.

  3. We create a URI object with the target URL (https://www.example.com).

  4. We use Net::HTTP.get_response(uri) to send a GET request and receive the response. This is a convenient method that handles creating the HTTP client and making the request.

  5. We print the response status using response.code and response.message.

  6. To print the first 5 lines of the response body, we use the lines method to split the body into an array of lines, take(5) to get the first 5 elements, and then iterate over them with each.

  7. We use chomp to remove the newline character at the end of each line when printing.

  8. We wrap our code in a begin/rescue block to handle potential network errors, such as when the host is unreachable.

To run this script:

  1. Save the code in a file, e.g., http_client.rb.
  2. Open a terminal and navigate to the directory containing the file.
  3. Run the script using the Ruby interpreter:
$ ruby http_client.rb

This will output the response status and the first 5 lines of the response body from the example.com website.

Ruby’s standard library provides a high-level interface for HTTP operations, making it easy to perform web requests. For more complex scenarios or advanced features, you might consider using external libraries like faraday or httparty, which offer additional functionality and a more flexible API.