Search code examples
curlrusttcp

Get CURL Easy response content-type


I am using the curl::easy::Easy crate in Rust to get data from HTTP.

I would like to know how I can get the content-type of the response as the documentation is not clear for me even when I set show_headers true.

Here is the code snippet.

    let mut easy = Easy::new();
    easy.url(url).unwrap();
    easy.show_header(true);
    easy.write_function(move |data| {
        fs::write(path_uri.as_str(), data);
        Ok(data.len())
    }).unwrap();
    easy.perform().unwrap();

Solution

  • Easy has a method named content_type, which seemingly is what you want.

    use curl::easy::Easy;
    
    fn main() {
        let mut easy = Easy::new();
        easy.url("https://www.rust-lang.org/").unwrap();
        easy.write_function(|data: &[u8]| {
            // stdout().write_all(data).unwrap();
            Ok(data.len())
        })
        .unwrap();
        easy.perform().unwrap();
    
        // get the content-type then print it
        let con_type: &str = easy.content_type().unwrap().unwrap();
        println!("{}", con_type);
    }
    
    $ cargo run -q
    text/html; charset=utf-8