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 their HttpError::status and the
connection is closed; the handler never sees them. Every response
gets a date header unless the handler set one.
§Errors
Only if accepting connections fails persistently; transient accept errors are retried.
§Examples
See Server.