Skip to main content

Conn

Struct Conn 

Source
pub struct Conn<Transport> { /* private fields */ }
Expand description

A http connection

Unlike in other rust http implementations, this struct represents both the request and the response, and holds the transport over which the response will be sent.

Implementations§

Source§

impl<Transport> Conn<Transport>

Source

pub fn context(&self) -> &HttpContext

Borrows the shared HttpContext

Source

pub fn request_headers(&self) -> &Headers

Borrows request headers

Source

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

Mutably borrow request headers

Source

pub fn response_headers(&self) -> &Headers

Borrows response headers

Source

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

Mutably borrow response headers

Source

pub fn method(&self) -> Method

Returns a copy of the http method for this conn’s request

let mut conn = Conn::new_synthetic(Method::Get, "/some/path?and&a=query", ());
assert_eq!(conn.method(), Method::Get);
Source

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

Sets the http method for this conn’s request, returning &mut Self for chaining

let mut conn = Conn::new_synthetic(Method::Get, "/some/path?and&a=query", ());
assert_eq!(conn.method(), Method::Get);
Source

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

Returns a copy of the http status for this conn, if set

Source

pub fn http_version(&self) -> Version

Returns a copy of the http version for this conn

Source

pub fn state(&self) -> &TypeSet

Borrows the state typemap for this conn

Source

pub fn state_mut(&mut self) -> &mut TypeSet

Mutably borrow the state typemap for this conn

Source

pub fn response_body(&self) -> Option<&Body>

Borrows the response body

HttpTest::new(|conn| async move { conn.with_response_body("hello") })
.get("/")
.block()
.assert_body("hello");

HttpTest::new(|conn| async move { conn.with_response_body(String::from("world")) })
.get("/")
.block()
.assert_body("world");

HttpTest::new(|conn| async move { conn.with_response_body(vec![99, 97, 116]) })
.get("/")
.block()
.assert_body("cat");
Source

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

Sets the response body, returning &mut Self for chaining

HttpTest::new(|conn| async move { conn.with_response_body("hello") })
.get("/")
.block()
.assert_body("hello");

HttpTest::new(|conn| async move { conn.with_response_body(String::from("world")) })
.get("/")
.block()
.assert_body("world");

HttpTest::new(|conn| async move { conn.with_response_body(vec![99, 97, 116]) })
.get("/")
.block()
.assert_body("cat");
Source

pub fn with_response_body(self, response_body: impl Into<Body>) -> Self

Owned chainable setter for the response body, returning Self

HttpTest::new(|conn| async move { conn.with_response_body("hello") })
.get("/")
.block()
.assert_body("hello");

HttpTest::new(|conn| async move { conn.with_response_body(String::from("world")) })
.get("/")
.block()
.assert_body("world");

HttpTest::new(|conn| async move { conn.with_response_body(vec![99, 97, 116]) })
.get("/")
.block()
.assert_body("cat");
Source

pub fn take_response_body(&mut self) -> Option<Body>

Takes the response body, leaving a None in its place

HttpTest::new(|conn| async move { conn.with_response_body("hello") })
.get("/")
.block()
.assert_body("hello");

HttpTest::new(|conn| async move { conn.with_response_body(String::from("world")) })
.get("/")
.block()
.assert_body("world");

HttpTest::new(|conn| async move { conn.with_response_body(vec![99, 97, 116]) })
.get("/")
.block()
.assert_body("cat");
Source

pub fn transport(&self) -> &Transport

Borrows the transport

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. If you’re looking to transition from HTTP to another protocol, use an HTTP upgrade.

Source

pub fn transport_mut(&mut self) -> &mut Transport

Mutably borrow the transport

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. If you’re looking to transition from HTTP to another protocol, use an HTTP upgrade.

Source

pub fn is_secure(&self) -> bool

Returns a copy of whether the connection is secure

note that this does not necessarily indicate that the transport itself is secure, as it may indicate that trillium_http is behind a trusted reverse proxy that has terminated tls and provided appropriate headers to indicate this.

Source

pub fn set_secure(&mut self, secure: bool) -> &mut Self

Sets whether the connection is secure, returning &mut Self for chaining

note that this does not necessarily indicate that the transport itself is secure, as it may indicate that trillium_http is behind a trusted reverse proxy that has terminated tls and provided appropriate headers to indicate this.

Source

pub fn start_time(&self) -> Instant

Returns a copy of The Instant that the first header bytes for this conn were received, before any processing or parsing has been performed.

Source

pub fn peer_ip(&self) -> Option<IpAddr>

Returns a copy of The IP Address for the connection, if available

Source

pub fn set_peer_ip(&mut self, peer_ip: Option<impl Into<IpAddr>>) -> &mut Self

Sets The IP Address for the connection, if available, returning &mut Self for chaining

Source

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

Borrows the :authority http/3 pseudo-header

Source

pub fn set_authority( &mut self, authority: Option<impl Into<Cow<'static, str>>>, ) -> &mut Self

Sets the :authority http/3 pseudo-header, returning &mut Self for chaining

Source

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

Borrows the :scheme http/3 pseudo-header

Source

pub fn set_scheme( &mut self, scheme: Option<impl Into<Cow<'static, str>>>, ) -> &mut Self

Sets the :scheme http/3 pseudo-header, returning &mut Self for chaining

Source

pub fn h3_connection(&self) -> Option<&H3Connection>

Borrows the H3Connection for this conn, if this is an HTTP/3 request

Source

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

Borrows the :protocol http/3 pseudo-header

Source

pub fn set_protocol( &mut self, protocol: Option<impl Into<Cow<'static, str>>>, ) -> &mut Self

Sets the :protocol http/3 pseudo-header, returning &mut Self for chaining

Source

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

Borrows request trailers, populated after the request body has been fully read

Source

pub fn request_trailers_mut(&mut self) -> Option<&mut Headers>

Mutably borrow request trailers, populated after the request body has been fully read

Source§

impl<Transport> Conn<Transport>
where Transport: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static,

Source

pub fn shared_state(&self) -> &TypeSet

Returns the shared state on this conn, if set

Source

pub fn set_status(&mut self, status: impl TryInto<Status>) -> &mut Self

sets the http status code from any TryInto<Status>.

assert!(conn.status().is_none());

conn.set_status(200); // a status can be set as a u16
assert_eq!(conn.status().unwrap(), Status::Ok);

conn.set_status(Status::ImATeapot); // or as a Status
assert_eq!(conn.status().unwrap(), Status::ImATeapot);
conn
Source

pub fn with_status(self, status: impl TryInto<Status>) -> Self

sets the http status code from any TryInto<Status>, returning Conn

Source

pub fn path(&self) -> &str

retrieves the path part of the request url, up to and excluding any query component

HttpTest::new(|mut conn| async move {
    assert_eq!(conn.path(), "/some/path");
    conn.with_status(200)
})
.get("/some/path?and&a=query")
.block()
.assert_ok();
Source

pub fn path_and_query(&self) -> &str

retrieves the combined path and any query

Source

pub fn querystring(&self) -> &str

retrieves the query component of the path, or an empty &str

let server = HttpTest::new(|conn| async move {
    let querystring = conn.querystring().to_string();
    conn.with_response_body(querystring).with_status(200)
});

server
    .get("/some/path?and&a=query")
    .block()
    .assert_body("and&a=query");

server.get("/some/path").block().assert_body("");
Source

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

get the host for this conn, if it exists

Source

pub fn set_host(&mut self, host: String) -> &mut Self

set the host for this conn

Source

pub async fn cancel_on_disconnect<'a, Fut>( &'a mut self, fut: Fut, ) -> Option<Fut::Output>
where Fut: Future + Send + 'a,

Cancels and drops the future if reading from the transport results in an error or empty read

The use of this method is not advised if your connected http client employs pipelining (rarely seen in the wild), as it will buffer an unbounded number of requests one byte at a time

If the client disconnects from the conn’s transport, this function will return None. If the future completes without disconnection, this future will return Some containing the output of the future.

Note that the inner future cannot borrow conn, so you will need to clone or take any information needed to execute the future prior to executing this method.

§Example
async fn something_slow_and_cancel_safe() -> String {
    String::from("this was not actually slow")
}
async fn handler<T>(mut conn: Conn<T>) -> Conn<T>
where
    T: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
{
    let Some(returned_body) = conn
        .cancel_on_disconnect(async { something_slow_and_cancel_safe().await })
        .await
    else {
        return conn;
    };
    conn.with_response_body(returned_body).with_status(200)
}
Source

pub async fn is_disconnected(&mut self) -> bool

Check if the transport is connected by attempting to read from the transport

§Example

This is best to use at appropriate points in a long-running handler, like:

async fn handler<T>(mut conn: Conn<T>) -> Conn<T>
where
    T: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
{
    for _ in 0..100 {
        if conn.is_disconnected().await {
            return conn;
        }
        something_slow_but_not_cancel_safe().await;
    }
    conn.with_status(200)
}
Source

pub fn request_encoding(&self) -> &'static Encoding

returns the encoding_rs::Encoding for this request, as determined from the mime-type charset, if available

HttpTest::new(|mut conn| async move {
    assert_eq!(conn.request_encoding(), encoding_rs::WINDOWS_1252); // the default

    conn.request_headers_mut()
        .insert("content-type", "text/plain;charset=utf-16");
    assert_eq!(conn.request_encoding(), encoding_rs::UTF_16LE);

    conn.with_status(200)
})
.get("/")
.block()
.assert_ok();
Source

pub fn response_encoding(&self) -> &'static Encoding

returns the encoding_rs::Encoding for this response, as determined from the mime-type charset, if available

HttpTest::new(|mut conn| async move {
    assert_eq!(conn.response_encoding(), encoding_rs::WINDOWS_1252); // the default
    conn.response_headers_mut()
        .insert("content-type", "text/plain;charset=utf-16");

    assert_eq!(conn.response_encoding(), encoding_rs::UTF_16LE);

    conn.with_status(200)
})
.get("/")
.block()
.assert_ok();
Source

pub fn request_body(&mut self) -> ReceivedBody<'_, Transport>

returns a ReceivedBody that references this conn. the conn retains all data and holds the singular transport, but the ReceivedBody provides an interface to read body content.

If the request included an Expect: 100-continue header, the 100 Continue response is sent lazily on the first read from the returned ReceivedBody.

let server = HttpTest::new(|mut conn| async move {
    let request_body = conn.request_body();
    assert_eq!(request_body.content_length(), Some(5));
    assert_eq!(request_body.read_string().await.unwrap(), "hello");
    conn.with_status(200)
});

server.post("/").with_body("hello").block().assert_ok();
Source

pub fn swansong(&self) -> Swansong

returns a clone of the swansong::Swansong for this Conn. use this to gracefully stop long-running futures and streams inside of handler functions

Source

pub fn after_send<F>(&mut self, after_send: F)
where F: FnOnce(SendStatus) + Send + Sync + 'static,

Registers a function to call after the http response has been completely transferred. Please note that this is a sync function and should be computationally lightweight. If your application needs additional async processing, use your runtime’s task spawn within this hook. If your library needs additional async processing in an after_send hook, please open an issue. This hook is currently designed for simple instrumentation and logging, and should be thought of as equivalent to a Drop hook.

Source

pub fn map_transport<NewTransport>( self, f: impl Fn(Transport) -> NewTransport, ) -> Conn<NewTransport>
where NewTransport: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,

applies a mapping function from one transport to another. This is particularly useful for boxing the transport. unless you’re sure this is what you’re looking for, you probably don’t want to be using this

Source

pub fn should_upgrade(&self) -> bool

whether this conn is suitable for an http upgrade to another protocol

Trait Implementations§

Source§

impl<Transport> Debug for Conn<Transport>

Source§

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

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

impl<Transport> From<Conn<Transport>> for Upgrade<Transport>

Source§

fn from(conn: Conn<Transport>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<Transport> Freeze for Conn<Transport>
where Transport: Freeze,

§

impl<Transport> !RefUnwindSafe for Conn<Transport>

§

impl<Transport> Send for Conn<Transport>
where Transport: Send,

§

impl<Transport> Sync for Conn<Transport>
where Transport: Sync,

§

impl<Transport> Unpin for Conn<Transport>
where Transport: Unpin,

§

impl<Transport> UnsafeUnpin for Conn<Transport>
where Transport: UnsafeUnpin,

§

impl<Transport> !UnwindSafe for Conn<Transport>

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

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.