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>
impl<Transport> Conn<Transport>
Sourcepub fn context(&self) -> &HttpContext
pub fn context(&self) -> &HttpContext
Borrows the shared HttpContext
Sourcepub fn request_headers(&self) -> &Headers
pub fn request_headers(&self) -> &Headers
Borrows request headers
Sourcepub fn request_headers_mut(&mut self) -> &mut Headers
pub fn request_headers_mut(&mut self) -> &mut Headers
Mutably borrow request headers
Sourcepub fn response_headers(&self) -> &Headers
pub fn response_headers(&self) -> &Headers
Borrows response headers
Sourcepub fn response_headers_mut(&mut self) -> &mut Headers
pub fn response_headers_mut(&mut self) -> &mut Headers
Mutably borrow response headers
Sourcepub fn method(&self) -> Method
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);Sourcepub fn set_method(&mut self, method: Method) -> &mut Self
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);Sourcepub fn http_version(&self) -> Version
pub fn http_version(&self) -> Version
Returns a copy of the http version for this conn
Sourcepub fn state(&self) -> &TypeSet
pub fn state(&self) -> &TypeSet
Borrows the state typemap for this conn
Sourcepub fn state_mut(&mut self) -> &mut TypeSet
pub fn state_mut(&mut self) -> &mut TypeSet
Mutably borrow the state typemap for this conn
Sourcepub fn response_body(&self) -> Option<&Body>
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");Sourcepub fn set_response_body(&mut self, response_body: impl Into<Body>) -> &mut Self
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");Sourcepub fn with_response_body(self, response_body: impl Into<Body>) -> Self
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");Sourcepub fn take_response_body(&mut self) -> Option<Body>
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");Sourcepub fn transport(&self) -> &Transport
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.
Sourcepub fn transport_mut(&mut self) -> &mut Transport
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.
Sourcepub fn is_secure(&self) -> bool
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.
Sourcepub fn set_secure(&mut self, secure: bool) -> &mut Self
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.
Sourcepub fn start_time(&self) -> Instant
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.
Sourcepub fn peer_ip(&self) -> Option<IpAddr>
pub fn peer_ip(&self) -> Option<IpAddr>
Returns a copy of The IP Address for the connection, if available
Sourcepub fn set_peer_ip(&mut self, peer_ip: Option<impl Into<IpAddr>>) -> &mut Self
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
Borrows the :authority http/3 pseudo-header
Sets the :authority http/3 pseudo-header, returning &mut Self for chaining
Sourcepub fn set_scheme(
&mut self,
scheme: Option<impl Into<Cow<'static, str>>>,
) -> &mut Self
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
Sourcepub fn h3_connection(&self) -> Option<&H3Connection>
pub fn h3_connection(&self) -> Option<&H3Connection>
Borrows the H3Connection for this conn, if this is an HTTP/3 request
Sourcepub fn set_protocol(
&mut self,
protocol: Option<impl Into<Cow<'static, str>>>,
) -> &mut Self
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
Sourcepub fn request_trailers(&self) -> Option<&Headers>
pub fn request_trailers(&self) -> Option<&Headers>
Borrows request trailers, populated after the request body has been fully read
Sourcepub fn request_trailers_mut(&mut self) -> Option<&mut Headers>
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>
impl<Transport> Conn<Transport>
Returns the shared state on this conn, if set
Sourcepub fn set_status(&mut self, status: impl TryInto<Status>) -> &mut Self
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);
connSourcepub fn with_status(self, status: impl TryInto<Status>) -> Self
pub fn with_status(self, status: impl TryInto<Status>) -> Self
sets the http status code from any TryInto<Status>, returning Conn
Sourcepub fn path(&self) -> &str
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();Sourcepub fn path_and_query(&self) -> &str
pub fn path_and_query(&self) -> &str
retrieves the combined path and any query
Sourcepub fn querystring(&self) -> &str
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("");Sourcepub async fn cancel_on_disconnect<'a, Fut>(
&'a mut self,
fut: Fut,
) -> Option<Fut::Output>
pub async fn cancel_on_disconnect<'a, Fut>( &'a mut self, fut: Fut, ) -> Option<Fut::Output>
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)
}Sourcepub async fn is_disconnected(&mut self) -> bool
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)
}Sourcepub fn request_encoding(&self) -> &'static Encoding
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();Sourcepub fn response_encoding(&self) -> &'static Encoding
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();Sourcepub fn request_body(&mut self) -> ReceivedBody<'_, Transport>
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();Sourcepub fn swansong(&self) -> Swansong
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
Sourcepub fn after_send<F>(&mut self, after_send: F)
pub fn after_send<F>(&mut self, after_send: F)
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.
Sourcepub fn map_transport<NewTransport>(
self,
f: impl Fn(Transport) -> NewTransport,
) -> Conn<NewTransport>
pub fn map_transport<NewTransport>( self, f: impl Fn(Transport) -> NewTransport, ) -> Conn<NewTransport>
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
Sourcepub fn should_upgrade(&self) -> bool
pub fn should_upgrade(&self) -> bool
whether this conn is suitable for an http upgrade to another protocol