Skip to main content

http_net/
lib.rs

1//! # http_net
2//!
3//! An HTTP/1.1 engine that does no I/O itself. Feed it the bytes a socket
4//! delivered; it hands back requests (or responses) as borrowed views of
5//! those bytes, decodes their bodies, and serializes what you send back.
6//! The caller owns sockets, threads, and timers, so the same core runs
7//! under a blocking loop, an event loop, or a test that never opens a
8//! socket.
9//!
10//! Parsing follows RFC 9112 strictly. Messages that recipients could
11//! disagree about are refused rather than repaired: conflicting
12//! `Content-Length` / `Transfer-Encoding`, duplicate `Content-Length`,
13//! obsolete line folding, bare CR or LF, whitespace before a colon, and
14//! control characters in field values each have their own [`HttpError`].
15//! Every buffer is bounded by [`Limits`], and each limit is checked before
16//! the bytes it governs are buffered.
17//!
18//! ## Tier 1: serve and fetch (blocking, `std`)
19//!
20//! ```
21//! # #[cfg(feature = "std")]
22//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
23//! use http_net::{blocking, Response};
24//!
25//! let server = blocking::Server::bind("127.0.0.1:0")?;
26//! let addr = server.local_addr();
27//! let stop = server.shutdown_handle();
28//! let t = std::thread::spawn(move || server.serve(|req, _body| Response::text(200, req.path())));
29//!
30//! let resp = blocking::get(&format!("http://{addr}/hi"))?;
31//! assert_eq!(resp.text(), Some("/hi"));
32//!
33//! stop.shutdown();
34//! t.join().unwrap()?;
35//! # Ok(())
36//! # }
37//! # #[cfg(not(feature = "std"))]
38//! # fn main() {}
39//! ```
40//!
41//! ## Tier 2: the sans-IO connection
42//!
43//! ```
44//! use http_net::{Response, ServerConn, ServerEvent};
45//!
46//! let mut conn = ServerConn::new();
47//! let mut out = Vec::new();
48//! let _ = conn.feed(b"GET /status HTTP/1.1\r\nHost: localhost\r\n\r\n");
49//! loop {
50//!     match conn.poll()? {
51//!         ServerEvent::Request(req) => assert_eq!(req.path(), "/status"),
52//!         ServerEvent::Body(_) => {}
53//!         ServerEvent::RequestEnd => conn.respond(&Response::text(200, "up"), &mut out)?,
54//!         _ => break, // NeedInput: read more from the socket
55//!     }
56//! }
57//! assert!(out.starts_with(b"HTTP/1.1 200 OK\r\n"));
58//! # Ok::<(), http_net::HttpError>(())
59//! ```
60//!
61//! [`ClientConn`] is the mirror image for the client side, and the
62//! `blocking` module shows how either is driven over `std::net`.
63//!
64//! ## Protocol upgrades
65//!
66//! A request with `Connection: upgrade` and an `Upgrade` field reports
67//! [`RequestHead::is_upgrade`]. Answering it with
68//! [`Response::switching_protocols`] moves the connection to
69//! [`ServerEvent::Upgraded`], after which
70//! [`ServerConn::remaining_input`] holds any bytes of the new protocol that
71//! arrived with the request. This is the hand-off point for a WebSocket
72//! engine such as `ws-net`.
73//!
74//! ## Feature flags
75//!
76//! | Feature | Default | Description |
77//! |---|---|---|
78//! | `std` | yes | The `blocking` adapter over `std::net`. Without it the crate is `no_std` and needs only `alloc`. |
79
80#![cfg_attr(not(feature = "std"), no_std)]
81#![cfg_attr(docsrs, feature(doc_cfg))]
82#![forbid(unsafe_code)]
83#![deny(missing_docs)]
84#![deny(unused_must_use)]
85#![deny(unused_results)]
86#![deny(clippy::unwrap_used)]
87#![deny(clippy::expect_used)]
88#![deny(clippy::todo)]
89#![deny(clippy::unimplemented)]
90#![deny(clippy::print_stdout)]
91#![deny(clippy::print_stderr)]
92#![deny(clippy::dbg_macro)]
93#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
94
95extern crate alloc;
96
97mod body;
98mod buffer;
99mod client;
100mod error;
101mod head;
102mod limits;
103mod message;
104mod server;
105mod syntax;
106
107#[cfg(feature = "std")]
108#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
109pub mod blocking;
110
111pub use client::{ClientConn, ClientEvent};
112pub use error::HttpError;
113pub use head::{BodyFraming, Headers, Method, RequestHead, ResponseHead, Version};
114pub use limits::Limits;
115pub use message::{Request, Response, reason_phrase};
116pub use server::{ServerConn, ServerEvent};
117
118// The README's examples run as doctests, so its claims stay true.
119#[cfg(all(doctest, feature = "std"))]
120#[doc = include_str!("../README.md")]
121struct ReadmeDoctests;
122
123#[cfg(test)]
124mod tests {
125    #[test]
126    fn test_public_types_are_send_and_sync() {
127        fn assert<T: Send + Sync>() {}
128        assert::<crate::ServerConn>();
129        assert::<crate::ClientConn>();
130        assert::<crate::Response>();
131        assert::<crate::Request>();
132        assert::<crate::HttpError>();
133        assert::<crate::Limits>();
134    }
135}