Struct trillium_http::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>
where Transport: AsyncRead + AsyncWrite + Unpin + Send + Sync + 'static,

source

pub async fn map<F, Fut>( transport: Transport, stopper: Stopper, handler: F ) -> Result<Option<Upgrade<Transport>>>
where F: Fn(Conn<Transport>) -> Fut, Fut: Future<Output = Conn<Transport>> + Send,

read any number of new Conns from the transport and call the provided handler function until either the connection is closed or an upgrade is requested. A return value of Ok(None) indicates a closed connection, while a return value of Ok(Some(upgrade)) represents an upgrade.

Provides a default HttpConfig

See the documentation for Conn for a full example.

Errors

This will return an error variant if:

  • there is an io error when reading from the underlying transport
  • headers are too long
  • we are unable to parse some aspect of the request
  • the request is an unsupported http version
  • we cannot make sense of the headers, such as if there is a content-length header as well as a transfer-encoding: chunked header.
source

pub async fn map_with_config<F, Fut>( http_config: HttpConfig, transport: Transport, stopper: Stopper, handler: F ) -> Result<Option<Upgrade<Transport>>>
where F: Fn(Conn<Transport>) -> Fut, Fut: Future<Output = Conn<Transport>> + Send,

read any number of new Conns from the transport and call the provided handler function until either the connection is closed or an upgrade is requested. A return value of Ok(None) indicates a closed connection, while a return value of Ok(Some(upgrade)) represents an upgrade.

See the documentation for Conn for a full example.

Errors

This will return an error variant if:

  • there is an io error when reading from the underlying transport
  • headers are too long
  • we are unable to parse some aspect of the request
  • the request is an unsupported http version
  • we cannot make sense of the headers, such as if there is a content-length header as well as a transfer-encoding: chunked header.
source

pub fn state(&self) -> &StateSet

returns a read-only reference to the state typemap for this conn

stability note: this is not unlikely to be removed at some point, as this may end up being more of a trillium concern than a trillium_http concern

source

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

returns a mutable reference to the state typemap for this conn

stability note: this is not unlikely to be removed at some point, as this may end up being more of a trillium concern than a trillium_http concern

source

pub fn request_headers(&self) -> &Headers

returns a reference to the request headers

source

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

returns a mutable reference to the response headers

source

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

returns a mutable reference to the response headers

source

pub fn response_headers(&self) -> &Headers

returns a reference to the response headers

source

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

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

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

retrieves the current response status code for this conn, if it has been set. See Conn::set_status for example usage.

source

pub fn path(&self) -> &str

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

let mut conn = Conn::new_synthetic(Method::Get, "/some/path?and&a=query", ());
assert_eq!(conn.path(), "/some/path");
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

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

let mut conn = Conn::new_synthetic(Method::Get, "/some/path", ());
assert_eq!(conn.querystring(), "");
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)

set the host for this conn

source

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

Sets the response body to anything that is impl Into<Body>.

conn.set_response_body("hello");
conn.set_response_body(String::from("hello"));
conn.set_response_body(vec![99, 97, 116]);
source

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

returns a reference to the current response body, if it has been set

source

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

remove the response body from this conn and return it

assert!(conn.response_body().is_none());
conn.set_response_body("hello");
assert!(conn.response_body().is_some());
let body = conn.take_response_body();
assert!(body.is_some());
assert!(conn.response_body().is_none());
source

pub fn method(&self) -> Method

returns 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)

overrides the http method for this conn

source

pub fn http_version(&self) -> Version

returns the http version for this conn.

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

let mut conn = Conn::new_synthetic(Method::Get, "/", ());
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);
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

let mut conn = Conn::new_synthetic(Method::Get, "/", ());
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);
source

pub async 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

let mut conn = Conn::new_synthetic(Method::Get, "/", "hello");
let request_body = conn.request_body().await;
assert_eq!(request_body.content_length(), Some(5));
assert_eq!(request_body.read_string().await.unwrap(), "hello");
source

pub fn stopper(&self) -> Stopper

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

source

pub async fn new( transport: Transport, bytes: Vec<u8>, stopper: Stopper ) -> Result<Self>

Create a new Conn

This function creates a new conn from the provided Transport, as well as any bytes that have already been read from the transport, and a Stopper instance that will be used to signal graceful shutdown.

Errors

This will return an error variant if:

  • there is an io error when reading from the underlying transport
  • headers are too long
  • we are unable to parse some aspect of the request
  • the request is an unsupported http version
  • we cannot make sense of the headers, such as if there is a content-length header as well as a transfer-encoding: chunked header.
source

pub fn is_secure(&self) -> bool

predicate function to indicate 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)

set whether the connection should be considered 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 finalize_headers(&mut self)

calculates any auto-generated headers for this conn prior to sending it

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 start_time(&self) -> Instant

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

source

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

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

Get a reference to the transport.

source

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

Get a mutable reference to 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 set_peer_ip(&mut self, peer_ip: Option<IpAddr>)

sets the remote ip address for this conn, if available.

source

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

retrieves the remote ip address for this conn, if available.

source§

impl Conn<Synthetic>

source

pub fn new_synthetic( method: Method, path: impl Into<String>, body: impl Into<Synthetic> ) -> Self

Construct a new synthetic conn with provided method, path, and body.

let conn = Conn::new_synthetic(Method::Get, "/", "hello");
assert_eq!(conn.method(), Method::Get);
assert_eq!(conn.path(), "/");
source

pub fn replace_body(&mut self, body: impl Into<Synthetic>)

Replaces the synthetic body. This is intended for testing use.

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

§

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.