Http Client in Crystal

Here’s the translation of the Go HTTP client example to Crystal:

Our example demonstrates how to make HTTP requests using Crystal’s standard library. We’ll use it to issue simple HTTP requests.

require "http/client"
require "uri"

# Issue an HTTP GET request to a server. HTTP::Client.get is a
# convenient method for making GET requests.
response = HTTP::Client.get("https://crystal-lang.org")

# Print the HTTP response status.
puts "Response status: #{response.status_code} #{response.status_message}"

# Print the first 5 lines of the response body.
response.body.each_line.first(5).each do |line|
  puts line
end

To run the program, save it as http_client.cr and use the crystal command:

$ crystal http_client.cr
Response status: 200 OK
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Crystal Programming Language</title>

This example demonstrates several key points:

  1. We use the HTTP::Client class from Crystal’s standard library to make HTTP requests.

  2. The HTTP::Client.get method is used to send a GET request to the specified URL. This method returns an HTTP::Client::Response object.

  3. We can access the response status using response.status_code and response.status_message.

  4. The response body is available through response.body. We use each_line to iterate over the lines of the body, first(5) to limit it to the first 5 lines, and then print each line.

  5. Crystal automatically handles resource management, so we don’t need to explicitly close the response body.

This example showcases Crystal’s simplicity and expressiveness when working with HTTP requests. The language provides a straightforward way to perform common web-related tasks.