Skip to main content

Conn

Struct 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 transport(&self) -> Option<&dyn Transport>

Borrows the transport for this conn

This should only be used to call your own custom methods on the transport that do not read or write any data. Calling any method that reads from or writes to the transport will disrupt the HTTP protocol.

Source

pub fn transport_mut(&mut self) -> Option<&mut dyn Transport>

Mutably borrow the transport for this conn

This should only be used to call your own custom methods on the transport that do not read or write any data. Calling any method that reads from or writes to the transport will disrupt the HTTP protocol.

Source

pub fn url(&self) -> &Url

Borrows the url for this conn.

use trillium_client::{Client, Method};
use trillium_testing::client_config;

let client = Client::from(client_config());

let conn = client.get("http://localhost:9080");

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

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

pub fn url_mut(&mut self) -> &mut Url

Mutably borrow the url for this conn.

use trillium_client::{Client, Method};
use trillium_testing::client_config;

let client = Client::from(client_config());

let conn = client.get("http://localhost:9080");

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

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

pub fn set_url(&mut self, url: Url) -> &mut Self

Sets the url for this conn., returning &mut Self for chaining

use trillium_client::{Client, Method};
use trillium_testing::client_config;

let client = Client::from(client_config());

let conn = client.get("http://localhost:9080");

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

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

pub fn method(&self) -> Method

Returns a copy of the method for this conn.

use trillium_client::{Client, Method};
use trillium_testing::client_config;

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

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

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

pub fn set_method(&mut self, method: Method) -> &mut Self

Sets the method for this conn., returning &mut Self for chaining

use trillium_client::{Client, Method};
use trillium_testing::client_config;

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

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

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

pub fn request_headers(&self) -> &Headers

Borrows the request headers

Source

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

Mutably borrow the request headers

Source

pub fn response_headers(&self) -> &Headers

Borrows the response headers

Source

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

Mutably borrow the response headers

Source

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

Returns a copy of the status code for this conn.

If the conn has not yet been sent, this will be None.

use trillium_client::{Client, Status};
use trillium_testing::{client_config, with_server};

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

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

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

Sets the request body, returning &mut Self for chaining

env_logger::init();
use trillium_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, |url| async move {
let client = Client::from(client_config());
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 with_body(self, body: impl Into<Body>) -> Self

Owned chainable setter for the request body, returning Self

env_logger::init();
use trillium_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, |url| async move {
let client = Client::from(client_config());
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 take_request_body(&mut self) -> Option<Body>

Takes the request body, leaving a None in its place

env_logger::init();
use trillium_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, |url| async move {
let client = Client::from(client_config());
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 timeout(&self) -> Option<Duration>

Returns a copy of the timeout for this conn

this can also be set on the client with Client::set_timeout and Client::with_timeout

Source

pub fn timeout_mut(&mut self) -> Option<&mut Duration>

Mutably borrow the timeout for this conn

this can also be set on the client with Client::set_timeout and Client::with_timeout

Source

pub fn set_timeout(&mut self, timeout: Duration) -> &mut Self

Sets the timeout for this conn, returning &mut Self for chaining

this can also be set on the client with Client::set_timeout and Client::with_timeout

Source

pub fn with_timeout(self, timeout: Duration) -> Self

Owned chainable setter for the timeout for this conn, returning Self

this can also be set on the client with Client::set_timeout and Client::with_timeout

Source

pub fn take_timeout(&mut self) -> Option<Duration>

Takes the timeout for this conn, leaving a None in its place

this can also be set on the client with Client::set_timeout and Client::with_timeout

Source

pub fn http_version(&self) -> Version

Returns a copy of the http version for this conn

prior to conn execution, this reflects the intended http version that will be sent, and after execution this reflects the server-indicated http version

Source

pub fn set_http_version(&mut self, http_version: Version) -> &mut Self

Sets the http version for this conn, returning &mut Self for chaining

prior to conn execution, this reflects the intended http version that will be sent, and after execution this reflects the server-indicated http version

Source

pub fn authority(&self) -> Option<&str>

Borrows the :authority pseudo-header, populated during h3 header finalization

Source

pub fn scheme(&self) -> Option<&str>

Borrows the :scheme pseudo-header, populated during h3 header finalization

Source

pub fn path(&self) -> Option<&str>

Borrows the :path pseudo-header, populated during h3 header finalization

Source

pub fn request_target(&self) -> Option<&str>

Borrows an explicit request target override, used only for OPTIONS * and CONNECT host:port

When set and the method is OPTIONS or CONNECT, this value is used as the HTTP request target instead of deriving it from the url. For all other methods, this field is ignored.

Source

pub fn set_request_target( &mut self, request_target: impl Into<Cow<'static, str>>, ) -> &mut Self

Sets an explicit request target override, used only for OPTIONS * and CONNECT host:port, returning &mut Self for chaining

When set and the method is OPTIONS or CONNECT, this value is used as the HTTP request target instead of deriving it from the url. For all other methods, this field is ignored.

Source

pub fn with_request_target( self, request_target: impl Into<Cow<'static, str>>, ) -> Self

Owned chainable setter for an explicit request target override, used only for OPTIONS * and CONNECT host:port, returning Self

When set and the method is OPTIONS or CONNECT, this value is used as the HTTP request target instead of deriving it from the url. For all other methods, this field is ignored.

Source

pub fn request_trailers(&self) -> Option<&Headers>

Borrows trailers sent with the request body, populated after the body has been fully sent.

Only present when the request body was constructed with Body::new_with_trailers and the body has been fully sent. For H3, this is populated after send_h3_request; for H1, after send_body with a chunked body.

Source

pub fn response_trailers(&self) -> Option<&Headers>

Borrows trailers received with the response body, populated after the response body has been fully read.

For H3, these are decoded from the trailing HEADERS frame. For H1, from chunked trailers (once H1 trailer receive is implemented).

Source§

impl Conn

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_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, |url| async move {
    let client = Client::new(client_config());
    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_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

use trillium_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, move |url| async move {
    let client = Client::new(client_config());
    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 without_request_header( self, name: impl Into<HeaderName<'static>>, ) -> Self

Chainable method to remove a request header if present

Source

pub fn with_json_body(self, body: &impl Serialize) -> Result<Self>

Available on crate feature sonic-rs only.

chainable setter for json body. this requires the sonic-rs crate feature to be enabled.

Source

pub fn response_body(&mut self) -> ResponseBody<'_>

returns a ResponseBody that borrows the connection inside this conn.

use trillium_client::Client;
use trillium_testing::{client_config, with_server};

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

with_server(handler, |url| async move {
    let client = Client::from(client_config());
    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 async fn response_json<T>(&mut self) -> Result<T, ClientSerdeError>

Available on crate feature sonic-rs only.

Attempt to deserialize the response body. Note that this consumes the body content.

Source

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

Returns the conn or an UnexpectedStatusError that contains the conn

use trillium_client::{Client, Status};
use trillium_testing::{client_config, with_server};

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

with_server(Status::Ok, |url| async move {
    let client = Client::new(client_config());
    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

Source

pub fn with_state<T: Send + Sync + 'static>(self, state: T) -> Self

add state to the client conn and return self

Source

pub fn insert_state<T: Send + Sync + 'static>(&mut self, state: T) -> Option<T>

add state to the client conn, returning any previously set state of this type

Source

pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>

borrow state

Source

pub fn state_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>

borrow state mutably

Source

pub fn take_state<T: Send + Sync + 'static>(&mut self) -> Option<T>

take state

Source§

impl Conn

Source

pub async fn into_websocket( self, ) -> Result<WebSocketConn, WebSocketUpgradeError>

Available on crate feature websockets only.

Attempt to transform this Conn into a WebSocketConn

This will:

  • set Upgrade, Connection, Sec-Websocket-Version, and Sec-Websocket-Key headers appropriately if they have not yet been set and the Conn has not yet been awaited
  • await the Conn if it has not yet been awaited
  • confirm websocket upgrade negotiation per rfc6455
  • transform the Conn into a WebSocketConn
Source

pub async fn into_websocket_with_config( self, config: WebSocketConfig, ) -> Result<WebSocketConn, WebSocketUpgradeError>

Available on crate feature websockets only.

Attempt to transform this Conn into a WebSocketConn, with a custom WebSocketConfig

This will:

  • set Upgrade, Connection, Sec-Websocket-Version, and Sec-Websocket-Key headers appropriately if they have not yet been set and the Conn has not yet been awaited
  • await the Conn if it has not yet been awaited
  • confirm websocket upgrade negotiation per rfc6455
  • transform the Conn into a WebSocketConn

Trait Implementations§

Source§

impl AsMut<TypeSet> for Conn

Source§

fn as_mut(&mut self) -> &mut TypeSet

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<TypeSet> for Conn

Source§

fn as_ref(&self) -> &TypeSet

Converts this type into a shared reference of the (usually inferred) input type.
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, Box<dyn Transport>>

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<Box<dyn Transport>>

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 From<WebSocketUpgradeError> for Conn

Available on crate feature websockets only.
Source§

fn from(value: WebSocketUpgradeError) -> Self

Converts to this type from the input type.
Source§

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

Source§

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§

type Output = Result<(), Error>

The output that the future will produce on completion.
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more
Source§

impl IntoFuture for Conn

Source§

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

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

type Output = Result<Conn, Error>

The output that the future will produce on completion.
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 UnsafeUnpin 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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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>,

Source§

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V