I'm doing a direct download of an MP3 audio stream via Rust. As this stream is indefinite, I want to be able to cancel it early to save what I have downloaded so far. Currently, I do this by pressing CTRL + C to stop the program. This results in a stream.mp3 file I can then play back and listen to, and while this works, it isn't ideal.
Given the following code, how could I programmatically stop io::copy()
early and have it save the file without killing the entire program?
extern crate reqwest;
use std::io;
use std::fs::File;
// Note that this is a direct link to the stream, not a webpage with HTML and a stream
const STREAM_URL: &str = "http://path.to/stream";
fn main() {
let mut response = reqwest::get(STREAM_URL)
.expect("Failed to request mp3 stream");
let mut output = File::create("stream.mp3")
.expect("Failed to create file!");
io::copy(&mut response, &mut output)
.expect("Failed to copy mp3 stream to file");
}
io::copy
.io::copy
's job is literally to copy the entire thing no matter what it is. You'd have to tellreqwest
to end the downloading somehow, but given thatreqwest
is mostly a convenience library aroundhyper
to download things simply, I also doubt it would have an API for this. Your next move would then to usehyper
directly, where cancelling a stream is just a matter of dropping its future. – Krell