How to download via HTTP only piece of big file with ruby

fetch, http, ruby

Solution

This seems to work when using sockets:

require 'socket'                  
host = "download.thinkbroadband.com"                 
path = "/1GB.zip" # get 1gb sample file
request = "GET #{path} HTTP/1.0\r\n\r\n"
socket = TCPSocket.open(host,80) 
socket.print(request)        

# find beginning of response body
buffer = ""                    
while !buffer.match("\r\n\r\n") do
  buffer += socket.read(1)  
end           

response = socket.read(100) #read first 100 bytes of body
puts response

I'm curious if there is a "ruby way".

Problem

I only need to download the first few kilobytes of a file via HTTP. I tried ``` require 'open-uri' url = 'http://example.com/big-file.dat' file = open(url) content = file.read(limit) ``` But it actually downloads the full file.

Original source