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
mainThis Ruby script demonstrates how to create a simple HTTP client using the standard library. Let’s break it down:
We start by requiring the necessary libraries:
net/httpfor HTTP functionality andurifor URI parsing.We define a
mainmethod to encapsulate our code, following a common Ruby practice for scripts.We create a
URIobject with the target URL (https://www.example.com).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.We print the response status using
response.codeandresponse.message.To print the first 5 lines of the response body, we use the
linesmethod to split the body into an array of lines,take(5)to get the first 5 elements, and then iterate over them witheach.We use
chompto remove the newline character at the end of each line when printing.We wrap our code in a
begin/rescueblock to handle potential network errors, such as when the host is unreachable.
To run this script:
- Save the code in a file, e.g.,
http_client.rb. - Open a terminal and navigate to the directory containing the file.
- Run the script using the Ruby interpreter:
$ ruby http_client.rbThis 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.