docs(server): Example for conn modules (#2277)

Add basic, module-level example for the Http struct in the server::conn module that shows how to customize the configuration of the HTTP protocol handling and then serve requests received through a tokio TCP stream.
This commit is contained in:
Stefano Buliani
2020-08-28 11:21:33 -07:00
committed by GitHub
parent 1ecbcbb119
commit 66fc127c8d

View File

@@ -7,6 +7,38 @@
//! //!
//! If you don't have need to manage connections yourself, consider using the //! If you don't have need to manage connections yourself, consider using the
//! higher-level [Server](super) API. //! higher-level [Server](super) API.
//!
//! ## Example
//! A simple example that uses the `Http` struct to talk HTTP over a Tokio TCP stream
//! ```no_run
//! use http::{Request, Response, StatusCode};
//! use hyper::{server::conn::Http, service::service_fn, Body};
//! use std::{net::SocketAddr, convert::Infallible};
//! use tokio::net::TcpListener;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! let addr: SocketAddr = ([127, 0, 0, 1], 8080).into();
//!
//! let mut tcp_listener = TcpListener::bind(addr).await?;
//! loop {
//! let (tcp_stream, _) = tcp_listener.accept().await?;
//! tokio::task::spawn(async move {
//! if let Err(http_err) = Http::new()
//! .http1_only(true)
//! .keep_alive(true)
//! .serve_connection(tcp_stream, service_fn(hello))
//! .await {
//! eprintln!("Error while serving HTTP connection: {}", http_err);
//! }
//! });
//! }
//! }
//!
//! async fn hello(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
//! Ok(Response::new(Body::from("Hello World!")))
//! }
//! ```
use std::error::Error as StdError; use std::error::Error as StdError;
use std::fmt; use std::fmt;