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:
We use the
HTTP::Client
class from Crystal’s standard library to make HTTP requests.The
HTTP::Client.get
method is used to send a GET request to the specified URL. This method returns anHTTP::Client::Response
object.We can access the response status using
response.status_code
andresponse.status_message
.The response body is available through
response.body
. We useeach_line
to iterate over the lines of the body,first(5)
to limit it to the first 5 lines, and then print each line.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.