From ab60deea733850f8c05e674620faac3f8aea2682 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 28 Mar 2023 11:01:59 -0500 Subject: [PATCH] Add Check If A URL Resolves To 200 as a Ruby TIL --- README.md | 3 ++- ruby/check-if-a-url-resolves-to-200.md | 29 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 ruby/check-if-a-url-resolves-to-200.md diff --git a/README.md b/README.md index 3ca82e1..727678a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1293 TILs and counting..._ +_1294 TILs and counting..._ --- @@ -1013,6 +1013,7 @@ _1293 TILs and counting..._ - [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md) - [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md) - [Check For Any Overlaps In List Of Ranges](ruby/check-for-any-overlaps-in-list-of-ranges.md) +- [Check If A URL Resolves To 200](ruby/check-if-a-url-resolves-to-200.md) - [Check If An Object Includes A Module](ruby/check-if-an-object-includes-a-module.md) - [Check Return Status Of Running A Shell Command](ruby/check-return-status-of-running-a-shell-command.md) - [Click On Text With Capybara](ruby/click-on-text-with-capybara.md) diff --git a/ruby/check-if-a-url-resolves-to-200.md b/ruby/check-if-a-url-resolves-to-200.md new file mode 100644 index 0000000..9de926d --- /dev/null +++ b/ruby/check-if-a-url-resolves-to-200.md @@ -0,0 +1,29 @@ +# Check If A URL Resolves To 200 + +Ruby's built-in [`Net::HTTP` +library](https://ruby-doc.org/stdlib-2.7.0/libdoc/net/http/rdoc/Net/HTTP.html) +allows us to make different kinds of HTTP requests. We can use it to make a +`HEAD` request which will request the status of a URL without actually fetching +its contents. + +We can work directly with `Net::HTTP` using strings, but I find it is easier +and less error-prone to get help from the `URI` class. + +To make a `#head` request, we first need to establish a connection to the host +with [the `#start` +method](https://ruby-doc.org/stdlib-2.7.0/libdoc/net/http/rdoc/Net/HTTP.html#method-i-start). +Then we can initiate our request from that connection object. + +```ruby +url = 'https://my.app.com/path/to/video.mp4' +uri = URI(url) +conn = Net::HTTP.start(uri.host, uri.port, use_ssl: true) +resp = conn.head(uri.path) + +resp.code +#=> "200" +``` + +We initiate the connection with the host and port of our URL. Then request the +`HEAD` response for the path of our URL. If we are working with an `https` URL, +we need to indicate that with `use_ssl: true` in the `#start` method options.