Trait ResponseExt

Source
pub trait ResponseExt {
    // Required methods
    fn header(&self, key: &str) -> Option<&str>;
    fn header_as<T: FromStr>(&self, key: &str) -> Option<T>;
    fn status_code(&self) -> u16;
}
Expand description

Extends http::request::Response with ergonomic extras for hreq.

These extensions are part of the primary goal of hreq to provide a “User first API”.

Required Methods§

Source

fn header(&self, key: &str) -> Option<&str>

Quickly read a header value as a &str.

A header value can in theory contain any byte value 32 to 255 (inclusive), excluding 127 (DEL). That means all possible header values are not representable as a &str.

In practice it’s incredibly rare for any header value to be outside US-ASCII, which means for the vast majority of cases &str is fine.

This convenience methods treats header values not representable as ascii as None.

use hreq::prelude::*;

let res = Request::get("http://httpbin.org/html")
    .call().block().unwrap();

let ctype = res.header("content-type").unwrap();

assert_eq!(ctype, "text/html; charset=utf-8");
Source

fn header_as<T: FromStr>(&self, key: &str) -> Option<T>

Quickly parse a header value into something else.

Rust fabulous FromStr trait means we can quickly parse a value into something else. For example, if we know a header x-req-id is supposed to have a numeric 64 bit value and we want that number, we can do:

use hreq::prelude::*;

let res = Request::get("https://my-api")
    .call().block().unwrap();

let req_id: u64 = res.header_as("x-req-id").unwrap();
Source

fn status_code(&self) -> u16

Get the response status code as a u16

These two are equivalent:

use hreq::prelude::*;

let res = Request::get("http://httpbin.org/get")
    .call().block().unwrap();

assert_eq!(res.status_code(), 200);

assert_eq!(res.status().as_u16(), 200);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<B> ResponseExt for Response<B>

Source§

fn header(&self, key: &str) -> Option<&str>

Source§

fn header_as<T: FromStr>(&self, key: &str) -> Option<T>

Source§

fn status_code(&self) -> u16

Implementors§