From 66fc127c8d4f81aed9300c9d0f13246b8206067a Mon Sep 17 00:00:00 2001 From: Stefano Buliani <2996317+sapessi@users.noreply.github.com> Date: Fri, 28 Aug 2020 11:21:33 -0700 Subject: [PATCH] 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. --- src/server/conn.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/server/conn.rs b/src/server/conn.rs index e0235b6a..9704899c 100644 --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -7,6 +7,38 @@ //! //! If you don't have need to manage connections yourself, consider using the //! 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> { +//! 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) -> Result, Infallible> { +//! Ok(Response::new(Body::from("Hello World!"))) +//! } +//! ``` use std::error::Error as StdError; use std::fmt;