Skip to main content

Crate trillium_http

Crate trillium_http 

Source
Expand description

This crate provides the http implementations for Trillium.

§Stability

As this is primarily intended for internal use by the Trillium crate, the api is likely to be less stable than that of the higher level abstractions in Trillium.

§Protocol dispatch

trillium-http supports HTTP/1.0, HTTP/1.1, HTTP/2, and (via trillium-quinn) HTTP/3 on the same listener. The version that a given connection speaks is decided at accept time:

ListenerALPN resultFirst bytesProtocol
TCP + TLSh2HTTP/2 over TLS
TCP + TLShttp/1.1HTTP/1.1 over TLS
TCP + TLSabsent or othermatch HTTP/2 preface (PRI * HTTP/2.0…)HTTP/2 “prior knowledge” over TLS
TCP + TLSabsent or otheranything elseHTTP/1.1 over TLS
TCP, cleartextmatch HTTP/2 prefaceHTTP/2 “prior knowledge” (h2c)
TCP, cleartextanything elseHTTP/1.x
QUICHTTP/3

h2c via the HTTP/1.1 Upgrade mechanism (RFC 7540 §3.2, removed in RFC 9113) is not supported — if an Upgrade: h2c header arrives on an h1 request it is logged and ignored.

The TLS acceptors shipped with trillium that advertise ALPN (trillium-rustls and trillium-openssl) advertise h2, http/1.1 automatically. trillium-native-tls does not surface ALPN. Users with custom TLS configs are responsible for advertising h2 themselves if h2 is desired. Clients on TLS stacks that don’t expose an ALPN knob can still reach h2 via the prior-knowledge preface path — ALPN comes back absent and the server peeks the first 24 bytes.

All h2/h3-specific tuning flows through HttpConfig — see its field documentation for the full list of knobs (stream / connection flow-control windows, max concurrent streams, max frame size, etc.).

§Example

This is an elaborate example that demonstrates some of trillium_http’s capabilities. Please note that trillium itself provides a much more usable interface on top of trillium_http, at very little cost.

fn main() -> trillium_http::Result<()> {
    smol::block_on(async {
        use async_net::TcpListener;
        use futures_lite::StreamExt;
        use std::sync::Arc;
        use trillium_http::HttpContext;

        let context = Arc::new(HttpContext::default());
        let listener = TcpListener::bind(("localhost", 0)).await?;
        let local_addr = listener.local_addr().unwrap();
        let server_handle = smol::spawn({
            let context = context.clone();
            async move {
                let mut incoming = context.swansong().interrupt(listener.incoming());

                while let Some(Ok(stream)) = incoming.next().await {
                    smol::spawn(context.clone().run(stream, |mut conn| async move {
                        conn.set_response_body("hello world");
                        conn.set_status(200);
                        conn
                    }))
                    .detach()
                }
            }
        });

        // this example uses the trillium client
        // any other http client would work here too
        let client = trillium_client::Client::new(trillium_smol::ClientConfig::default())
            .with_base(local_addr);
        let mut client_conn = client.get("/").await?;

        assert_eq!(client_conn.status().unwrap(), 200);
        assert_eq!(
            client_conn.response_headers().get_str("content-length"),
            Some("11")
        );
        assert_eq!(
            client_conn.response_body().read_string().await?,
            "hello world"
        );

        context.shut_down().await; // stop the server after one request
        server_handle.await; // wait for the server to shut down
        Ok(())
    })
}

Re-exports§

pub use headers::HeaderName;
pub use headers::HeaderValue;
pub use headers::HeaderValues;
pub use headers::Headers;
pub use headers::KnownHeaderName;
pub use headers::SERVER_HEADER;
pub use type_set;

Modules§

h2
Trillium HTTP/2 types (RFC 9113).
h3
Trillium HTTP/3 types
headers
Header types

Structs§

Body
The trillium representation of a http body. This can contain either &'static [u8] content, Vec<u8> content, or a boxed AsyncRead/BodySource type.
Conn
A http connection
HttpConfig
Performance and security parameters for trillium-http.
HttpContext
This struct represents the shared configuration and context for a http server.
ReceivedBody
A received http body
Swansong
🦢 Shutdown manager
TypeSet
A collection for heterogenous types
Upgrade
This struct represents a http upgrade. It contains all of the data available on a Conn, as well as owning the underlying transport.

Enums§

ConnectionStatus
This represents the next state after a response on a conn transport.
Error
Concrete errors that occur within trillium’s HTTP implementation
Method
HTTP request methods.
Status
HTTP response status codes.
Version
The version of the HTTP protocol in use.

Constants§

CRATE_VERSION
The version of this crate
SERVICE_UNAVAILABLE
A pre-rendered http response to send when the server is at capacity.

Traits§

BodySource
Trait for streaming body sources that can optionally produce trailers.

Functions§

run_with_initial_bytes
Like HttpContext::run, but starts with the supplied bytes pre-filled into the request buffer.

Type Aliases§

Result
this crate’s result type