|
24 | 24 | //!
|
25 | 25 | //! # Example
|
26 | 26 | //!
|
| 27 | +//! __HTTP client__ |
| 28 | +//! |
| 29 | +//! ```no_run |
| 30 | +//! use async_h1::client; |
| 31 | +//! use async_std::net::{TcpStream}; |
| 32 | +//! use http_types::{Error, Method, Request, Url}; |
| 33 | +//! |
| 34 | +//! #[async_std::main] |
| 35 | +//! async fn main() -> Result<(), Error> { |
| 36 | +//! let stream = TcpStream::connect("127.0.0.1:8080").await?; |
| 37 | +//! let peer_addr = stream.peer_addr()?; |
| 38 | +//! println!("connecting to {}", peer_addr); |
| 39 | +//! |
| 40 | +//! for i in 0usize..2 { |
| 41 | +//! println!("making request {}/2", i + 1); |
| 42 | +//! let url = Url::parse(&format!("http://{}/foo", peer_addr)).unwrap(); |
| 43 | +//! let req = Request::new(Method::Get, dbg!(url)); |
| 44 | +//! let res = client::connect(stream.clone(), req).await?; |
| 45 | +//! println!("{:?}", res); |
| 46 | +//! } |
| 47 | +//! Ok(()) |
| 48 | +//! } |
27 | 49 | //! ```
|
28 |
| -//! // tbi |
| 50 | +//! |
| 51 | +//! __HTTP Server__ |
| 52 | +//! |
| 53 | +//! ```no_run |
| 54 | +//! use async_std::net::{TcpStream, TcpListener}; |
| 55 | +//! use async_std::prelude::*; |
| 56 | +//! use async_std::task; |
| 57 | +//! use http_types::{Response, StatusCode}; |
| 58 | +//! |
| 59 | +//! #[async_std::main] |
| 60 | +//! async fn main() -> http_types::Result<()> { |
| 61 | +//! // Open up a TCP connection and create a URL. |
| 62 | +//! let listener = TcpListener::bind(("127.0.0.1", 8080)).await?; |
| 63 | +//! let addr = format!("http://{}", listener.local_addr()?); |
| 64 | +//! println!("listening on {}", addr); |
| 65 | +//! |
| 66 | +//! // For each incoming TCP connection, spawn a task and call `accept`. |
| 67 | +//! let mut incoming = listener.incoming(); |
| 68 | +//! while let Some(stream) = incoming.next().await { |
| 69 | +//! let stream = stream?; |
| 70 | +//! let addr = addr.clone(); |
| 71 | +//! task::spawn(async { |
| 72 | +//! if let Err(err) = accept(addr, stream).await { |
| 73 | +//! eprintln!("{}", err); |
| 74 | +//! } |
| 75 | +//! }); |
| 76 | +//! } |
| 77 | +//! Ok(()) |
| 78 | +//! } |
| 79 | +//! |
| 80 | +//! // Take a TCP stream, and convert it into sequential HTTP request / response pairs. |
| 81 | +//! async fn accept(addr: String, stream: TcpStream) -> http_types::Result<()> { |
| 82 | +//! println!("starting new connection from {}", stream.peer_addr()?); |
| 83 | +//! async_h1::accept(&addr, stream.clone(), |_req| async move { |
| 84 | +//! let mut res = Response::new(StatusCode::Ok); |
| 85 | +//! res.insert_header("Content-Type", "text/plain")?; |
| 86 | +//! res.set_body("Hello"); |
| 87 | +//! Ok(res) |
| 88 | +//! }) |
| 89 | +//! .await?; |
| 90 | +//! Ok(()) |
| 91 | +//! } |
29 | 92 | //! ```
|
30 | 93 |
|
31 | 94 | // #![forbid(unsafe_code, rust_2018_idioms)]
|
|
0 commit comments