curl-rust icon indicating copy to clipboard operation
curl-rust copied to clipboard

one of your examples doesnt work

Open lever1209 opened this issue 10 months ago • 3 comments

use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    let mut transfer = easy.transfer();
    transfer.write_function(|data| {
        dst.extend_from_slice(data);
        Ok(data.len())
    }).unwrap();
    transfer.perform().unwrap();
	println!("{:?}", dst);
}

ive added that last println! line as a basic way to show theres no way to access the data after its written to, unless im missing something fundamental about closures

lever1209 avatar Aug 20 '23 19:08 lever1209

The closure passed to write_function borrows dst. The transfer object holds onto that closure until the transfer is dropped, meaning that dst is also now borrowed until transfer is dropped. To access dst you need to ensure the transfer is dropped to guarantee it will not write any further to dst. In this short example you could do that like this:

use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    {
        let mut transfer = easy.transfer();
        transfer.write_function(|data| {
            dst.extend_from_slice(data);
            Ok(data.len())
        }).unwrap();
        transfer.perform().unwrap();
    }

    println!("{:?}", dst);
}

or more explicitly like this:

use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    let mut transfer = easy.transfer();
    transfer.write_function(|data| {
        dst.extend_from_slice(data);
        Ok(data.len())
    }).unwrap();
    transfer.perform().unwrap();
    drop(transfer);

    println!("{:?}", dst);
}

Hope that helps!

sagebind avatar Aug 21 '23 20:08 sagebind

i already tried that and it didnt work, maybe i missed something

but ive already moved the project to a shell script and its 90% done

lever1209 avatar Aug 21 '23 21:08 lever1209

Best to Use Easy2.

LorenzoLeonardo avatar Oct 19 '23 21:10 LorenzoLeonardo