Hyper get response header



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.


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


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.


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?


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.


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