Check if a remotely file exist

Hi, as the title say, actually in my software development, I just would like to check if an archive at a specific address exist or not. This archive is public (don’t need authentification).

How can I do that?

Just to explain, when my software manager downloaded the source for a software, I would like it to check if there is any archive with inside patches, if the file don’t exist online, it’s because actually no patches exist.

Package are at: ism-mirror.co.uk/sources/sources_archive_name.tar.xz
Patches are at: ism-mirror.co.uk/patches/patches_archive_name.tar.xz

Not sure I follow 100%. Wouldn’t this just be a case where if a HEAD request results in a 404, it means it doesn’t exist and a 200 means it does?

Yeah I think it’s what I am looking for, it’s just I am not very good for web

So how I have to proceed ?

you’ll want to start by looking at the HTTP::Client.head class method, which will return a HTTP::Client::Response. you can then check the response’s #status to see if it is equal to HTTP::Status::NOT_FOUND (indicating the file was not found).

So definitely I think I am very bad for networking. I did that, but I get always the message exist, even it doesn’t exist:

require "http/client"

response = HTTP::Client.head("ism-mirror.co.uk/sources/Gcc-11.2.0.tar.xz.dontexist")

if response.status == HTTP::Status::NOT_FOUND
    puts "Doesnt exist"
else
    puts "Exist !"
end

okay, so your code is correct. the issue is here is that the server is trying to be helpful by returning a HTTP status of 300 which means that the request has more than one possible file (or in this case, similarly named files that you may have incorrectly typed).

there are a couple of alternatives that should work for you, however, it really depends on how much handling of the HTTP status codes you want to do.

perhaps the simplest solution for you could be changing the if statement to check if the response was a #success? or by comparing the response’s status against HTTP::Status::OK (200) both of which would indicate that the file is available.

2 Likes