pub struct Server { /* private fields */ }std only.Expand description
A blocking HTTP/1.1 server: one thread per connection, bounded.
§Examples
use http_net::{blocking::{self, Server}, Response};
let server = Server::bind("127.0.0.1:0")?;
let addr = server.local_addr();
let stop = server.shutdown_handle();
let thread = std::thread::spawn(move || {
server.serve(|req, _body| Response::text(200, &format!("you asked for {}", req.path())))
});
let resp = blocking::get(&format!("http://{addr}/hello"))?;
assert_eq!(resp.status(), 200);
assert_eq!(resp.text(), Some("you asked for /hello"));
stop.shutdown();
thread.join().unwrap()?;Implementations§
Source§impl Server
impl Server
Sourcepub fn bind(addr: impl ToSocketAddrs) -> Result<Self>
pub fn bind(addr: impl ToSocketAddrs) -> Result<Self>
Binds a listening socket. Use 127.0.0.1:0 for an ephemeral
localhost port and read it back with local_addr.
§Errors
The bind error from the operating system.
§Examples
let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
assert!(server.local_addr().ip().is_loopback());Sourcepub fn with_config(self, config: ServerConfig) -> Self
pub fn with_config(self, config: ServerConfig) -> Self
Replaces the configuration.
§Examples
use http_net::blocking::{Server, ServerConfig};
let s = Server::bind("127.0.0.1:0")?.with_config(ServerConfig::new().with_max_connections(4));Sourcepub fn local_addr(&self) -> SocketAddr
pub fn local_addr(&self) -> SocketAddr
The bound address (with the real port when bound to port 0).
§Examples
let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
assert_ne!(server.local_addr().port(), 0);Sourcepub fn shutdown_handle(&self) -> ShutdownHandle
pub fn shutdown_handle(&self) -> ShutdownHandle
Sourcepub fn serve<H>(self, handler: H) -> Result<()>
pub fn serve<H>(self, handler: H) -> Result<()>
Serves handler until ShutdownHandle::shutdown is called.
The handler gets each request’s head and its complete body (bounded
by Limits::max_body) and returns the response. Requests that fail
to parse are answered with Response::from_error and the
connection is closed; the handler never sees them. A request with
Expect: 100-continue gets 100 Continue before its body is read;
one with any other expectation is answered 417 Expectation Failed
without reading its body (RFC 9110 section 10.1.1), and the
connection is closed. A handler that returns a streamed response
(chunked or content_length, except to HEAD), or one that
ServerConn::respond refuses, is replaced by a 500 with
connection: close. Every response gets a date field (from
now_date) unless the handler set one, except the 503 sent to a
connection over the connection cap. The time limits and the request
cap of ServerConfig apply to every connection.
§Errors
Only if accepting connections fails persistently; transient accept errors are retried. Before the error is returned, live connections finish their current exchange, as after a shutdown.
§Examples
See Server.