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

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

Open tsnoam opened this issue 7 months ago • 3 comments

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!();
}

tsnoam avatar Nov 26 '23 14:11 tsnoam

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.

sagebind avatar Nov 26 '23 21:11 sagebind

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 avatar Nov 27 '23 08:11 tsnoam

@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?

tsnoam avatar Nov 30 '23 11:11 tsnoam