alexcrichton / curl-rust

Rust bindings to libcurl
MIT License
1k stars 234 forks source link

add mime support (form api is deprecated according to libcurl) #537

Open tsnoam opened 7 months ago

tsnoam commented 7 months ago

libcurl considers the form api deprecated. in curl_formadd(3) one of the first lines says:

This function is deprecated. Use curl_mime_init(3) instead.

This pull requests implements a safe wrapper of the mime api, keeping simplicity in mind. Usage is quite straight forward.

The following example is a bit simplified (lot of unwraps, usage of &str where possible.


fn main() {
    let filenames = &[ "/path/to/file1", "/path/to/file2" ];
    curl::init();
    let mut client = curl::easy::Easy::new();

    // interesting part starts here

    let mut mime = client.add_mime();
    for fname in filenames.iter() {
        let buf = read_file(fname)?;  // 
        mime.add_part()
            .set_name("some-name").unwrap()
            .set_filename(fname.rsplit_once('/').unwrap().1).unwrap()
            .set_data(buf).unwrap()
            .set_content_type("application/octet-stream").unwrap();
    }
    mime.post()?;

    // make sure not to call client.post/get/put/custom_request() as it will modify stuff inside libcurl causing it to behave
    // not as you intended (this comment is also true fort the deprecated form api)

    // interesting part ends here

    client.url("http://127.0.0.1/").unwrap();
    client.perform().unwrap();
}

/// Read a file into Vec<u8> - implementation is an exercise for the reader
fn read_file(fname: &str) -> Result<Vec<u8>, Error> {
    todo!();
}
sagebind commented 7 months ago

We support linking against libcurl versions older than 7.56.0 (when the mime API was added) so this will need to be behind an opt-in feature to avoid breaking compatibility with those older versions.

tsnoam commented 7 months ago

We support linking against libcurl versions older than 7.56.0 (when the mime API was added) so this will need to be behind an opt-in feature to avoid breaking compatibility with those older versions.

Ok. Done.

tsnoam commented 7 months ago

@sagebind I've adhered to your comments (except for the one I replied with a question of my own). Is there anything else you would to see?