Struct trillium_client::Conn

source ·
pub struct Conn { /* private fields */ }
Expand description

a client connection, representing both an outbound http request and a http response

Implementations§

source§

impl Conn

source

pub fn request_headers(&self) -> &Headers

borrow the request headers

source

pub fn with_request_header( self, name: impl Into<HeaderName<'static>>, value: impl Into<HeaderValues>, ) -> Self

chainable setter for inserting a request header

use trillium_testing::ClientConfig;


let handler = |conn: trillium::Conn| async move {
    let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
    let response = format!("some-request-header was {}", header);
    conn.ok(response)
};

let client = trillium_client::Client::new(ClientConfig::new());

trillium_testing::with_server(handler, |url| async move {
    let mut conn = client.get(url)
        .with_request_header("some-request-header", "header-value") // <--
        .await?;
    assert_eq!(
        conn.response_body().read_string().await?,
        "some-request-header was header-value"
    );
    Ok(())
})
source

pub fn with_header( self, name: impl Into<HeaderName<'static>>, value: impl Into<HeaderValues>, ) -> Self

👎Deprecated: use Conn::with_request_header

see [`with_request_header]

source

pub fn with_request_headers<HN, HV, I>(self, headers: I) -> Self
where I: IntoIterator<Item = (HN, HV)> + Send, HN: Into<HeaderName<'static>>, HV: Into<HeaderValues>,

chainable setter for extending request headers

let handler = |conn: trillium::Conn| async move {
    let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
    let response = format!("some-request-header was {}", header);
    conn.ok(response)
};

use trillium_testing::ClientConfig;
let client = trillium_client::client(ClientConfig::new());

trillium_testing::with_server(handler, move |url| async move {
    let mut conn = client.get(url)
        .with_request_headers([ // <--
            ("some-request-header", "header-value"),
            ("some-other-req-header", "other-header-value")
        ])
        .await?;
    assert_eq!(
        conn.response_body().read_string().await?,
        "some-request-header was header-value"
    );
    Ok(())
})
source

pub fn with_headers<HN, HV, I>(self, headers: I) -> Self
where I: IntoIterator<Item = (HN, HV)> + Send, HN: Into<HeaderName<'static>>, HV: Into<HeaderValues>,

👎Deprecated: use Conn::with_request_headers

see [with_request_headers]

source

pub fn without_request_header( self, name: impl Into<HeaderName<'static>>, ) -> Self

Chainable method to remove a request header if present

source

pub fn without_header(self, name: impl Into<HeaderName<'static>>) -> Self

👎Deprecated: use Conn::without_request_header

see [without_request_header]

source

pub fn response_headers(&self) -> &Headers

let handler = |conn: trillium::Conn| async move {
    conn.with_response_header("some-header", "some-value")
        .with_status(200)
};

use trillium_client::Client;
use trillium_testing::ClientConfig;

trillium_testing::with_server(handler, move |url| async move {
    let client = Client::new(ClientConfig::new());
    let conn = client.get(url).await?;

    let headers = conn.response_headers(); //<-

    assert_eq!(headers.get_str("some-header"), Some("some-value"));
    Ok(())
})
source

pub fn request_headers_mut(&mut self) -> &mut Headers

retrieves a mutable borrow of the request headers, suitable for appending a header. generally, prefer using chainable methods on Conn

use trillium_testing::ClientConfig;
use trillium_client::Client;

let handler = |conn: trillium::Conn| async move {
    let header = conn.request_headers().get_str("some-request-header").unwrap_or_default();
    let response = format!("some-request-header was {}", header);
    conn.ok(response)
};

let client = Client::new(ClientConfig::new());

trillium_testing::with_server(handler, move |url| async move {
    let mut conn = client.get(url);

    conn.request_headers_mut() //<-
        .insert("some-request-header", "header-value");

    let mut conn = conn.await?;

    assert_eq!(
        conn.response_body().read_string().await?,
        "some-request-header was header-value"
    );
    Ok(())
})
source

pub fn response_headers_mut(&mut self) -> &mut Headers

get a mutable borrow of the response headers

source

pub fn set_request_body(&mut self, body: impl Into<Body>)

sets the request body on a mutable reference. prefer the chainable Conn::with_body wherever possible

env_logger::init();
use trillium_client::Client;
use trillium_testing::ClientConfig;


let handler = |mut conn: trillium::Conn| async move {
    let body = conn.request_body_string().await.unwrap();
    conn.ok(format!("request body was: {}", body))
};

trillium_testing::with_server(handler, move |url| async move {
    let client = Client::new(ClientConfig::new());
    let mut conn = client.post(url);

    conn.set_request_body("body"); //<-

    (&mut conn).await?;

    assert_eq!(conn.response_body().read_string().await?, "request body was: body");
    Ok(())
});
source

pub fn with_body(self, body: impl Into<Body>) -> Self

chainable setter for the request body

env_logger::init();
use trillium_testing::ClientConfig;
use trillium_client::Client;

let handler = |mut conn: trillium::Conn| async move {
    let body = conn.request_body_string().await.unwrap();
    conn.ok(format!("request body was: {}", body))
};


trillium_testing::with_server(handler, |url| async move {
    let client = Client::from(ClientConfig::default());
    let mut conn = client.post(url)
        .with_body("body") //<-
        .await?;

    assert_eq!(
        conn.response_body().read_string().await?,
        "request body was: body"
    );
    Ok(())
});
source

pub fn url(&self) -> &Url

retrieves the url for this conn.

use trillium_testing::ClientConfig;
use trillium_client::Client;
let client = Client::from(ClientConfig::new());
let conn = client.get("http://localhost:9080");

let url = conn.url(); //<-

assert_eq!(url.host_str().unwrap(), "localhost");
source

pub fn method(&self) -> Method

retrieves the url for this conn.

use trillium_testing::ClientConfig;
use trillium_client::Client;

use trillium_testing::prelude::*;

let client = Client::from(ClientConfig::new());
let conn = client.get("http://localhost:9080");

let method = conn.method(); //<-

assert_eq!(method, Method::Get);
source

pub fn response_body(&mut self) -> ReceivedBody<'_, BoxedTransport>

returns a ReceivedBody that borrows the connection inside this conn.

env_logger::init();
use trillium_testing::ClientConfig;
use trillium_client::Client;



let handler = |mut conn: trillium::Conn| async move {
    conn.ok("hello from trillium")
};

trillium_testing::with_server(handler, |url| async move {
    let client = Client::from(ClientConfig::new());
    let mut conn = client.get(url).await?;

    let response_body = conn.response_body(); //<-

    assert_eq!(19, response_body.content_length().unwrap());
    let string = response_body.read_string().await?;
    assert_eq!("hello from trillium", string);
    Ok(())
});
source

pub fn status(&self) -> Option<Status>

returns the status code for this conn. if the conn has not yet been sent, this will be None.

use trillium_testing::ClientConfig;
use trillium_client::Client;
use trillium_testing::prelude::*;

async fn handler(conn: trillium::Conn) -> trillium::Conn {
    conn.with_status(418)
}

trillium_testing::with_server(handler, |url| async move {
    let client = Client::new(ClientConfig::new());
    let conn = client.get(url).await?;
    assert_eq!(Status::ImATeapot, conn.status().unwrap());
    Ok(())
});
source

pub fn success(self) -> Result<Self, UnexpectedStatusError>

Returns the conn or an UnexpectedStatusError that contains the conn

use trillium_testing::ClientConfig;

trillium_testing::with_server(trillium::Status::NotFound, |url| async move {
    let client = trillium_client::Client::new(ClientConfig::new());
    assert_eq!(
        client.get(url).await?.success().unwrap_err().to_string(),
        "expected a success (2xx) status code, but got 404 Not Found"
    );
    Ok(())
});

trillium_testing::with_server(trillium::Status::Ok, |url| async move {
    let client = trillium_client::Client::new(ClientConfig::new());
    assert!(client.get(url).await?.success().is_ok());
    Ok(())
});
source

pub async fn recycle(self)

Returns this conn to the connection pool if it is keepalive, and closes it otherwise. This will happen asynchronously as a spawned task when the conn is dropped, but calling it explicitly allows you to block on it and control where it happens.

source

pub fn peer_addr(&self) -> Option<SocketAddr>

attempts to retrieve the connected peer address

Trait Implementations§

source§

impl Debug for Conn

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Conn

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl From<Conn> for Body

source§

fn from(conn: Conn) -> Body

Converts to this type from the input type.
source§

impl From<Conn> for ReceivedBody<'static, BoxedTransport>

source§

fn from(conn: Conn) -> Self

Converts to this type from the input type.
source§

impl From<Conn> for UnexpectedStatusError

source§

fn from(value: Conn) -> Self

Converts to this type from the input type.
source§

impl From<Conn> for Upgrade<BoxedTransport>

source§

fn from(conn: Conn) -> Self

Converts to this type from the input type.
source§

impl From<UnexpectedStatusError> for Conn

source§

fn from(value: UnexpectedStatusError) -> Self

Converts to this type from the input type.
source§

impl<'conn> IntoFuture for &'conn mut Conn

§

type Output = Result<(), Error>

The output that the future will produce on completion.
§

type IntoFuture = Pin<Box<dyn Future<Output = <&'conn mut Conn as IntoFuture>::Output> + Send + 'conn>>

Which kind of future are we turning this into?
source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more
source§

impl IntoFuture for Conn

§

type Output = Result<Conn, Error>

The output that the future will produce on completion.
§

type IntoFuture = Pin<Box<dyn Future<Output = <Conn as IntoFuture>::Output> + Send>>

Which kind of future are we turning this into?
source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

§

impl Freeze for Conn

§

impl !RefUnwindSafe for Conn

§

impl Send for Conn

§

impl Sync for Conn

§

impl Unpin for Conn

§

impl !UnwindSafe for Conn

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.