Hyper get response header


#1

Hi,

I want to get response header such as Content-Length from hyper.
I wrote this code but I have no idea how can I get the Content-Length header?

    let mut response = match client.get("http://google.com").send() {
            Ok(response) => response,
            Err(why) => panic!("{}", why),
    };

also I couldn’t find any sample in documentaion.


#2

I found it :smiley:

let headers = std::mem::replace(&mut response.headers, hyper::header::Headers::new());
let content_length_header = headers.get_raw("Content-Length").unwrap();
    

#3

More idiomatically, you can do this:

use hyper::header::ContentLength;
let response = client.get("http://google.com").send().unwrap();
match response.headers.get::<ContentLength>() {
    Some(length) => { ... }
    None => { println!("Content-Length header missing") }
}

This is nice because then you don’t have to do the bytes->integer conversion yourself.


#4

I’ve been running into a similar issue with reqwest which is based on hyper and uses hyper’s headers. I haven’t found a way past it yet. I have this snippet of dealing with a response.

let mut n_bytes: u64 = 0;
match res.headers().get::<ContentLength>() {
    Some(length) => { n_bytes = *length as u64; }
    None => { println!("Content-Length header missing") }
}

Which is resulting in an error about non-scalar casts. Specifically:

error: non-scalar cast: reqwest::header::ContentLength as u64

Is there something I’m missing with regard to getting Content-Length header as a u64?


#5

length here is a ContentLength type; you can’t use as to cast it, you have to do length.0 to get the u64 out of wrapper.


#6

That works. Thanks! In case anyone else is curious about the length.0 notation, see Tuple Structs.