//! # HTTP Response Example //! //! This example demonstrates how to use the `Response` struct from the `http-handle` library //! to create and send HTTP responses over a TCP stream. The example includes creating a response //! with status codes, headers, and a body, and then sending it to a client. //! //! ## Usage //! Add the following to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! http-handle = "0.1" //! ``` //! //! Then, run the example using: //! ```sh //! cargo run --example response_example //! ``` use http_handle::response::Response; use http_handle::ServerError; use std::io::{ErrorKind, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::thread; /// Entry point for the HTTP response example. /// /// This function sets up a simple TCP listener that accepts a connection and sends an HTTP response /// back to the client. fn main() -> Result<(), ServerError> { println!("\n๐งช HTTP Response Example\n"); // Start a TCP listener on localhost:8080 let listener = TcpListener::bind("127.0.0.1:8080")?; println!("โ Listening on 127.0.0.1:8080"); // Spawn a thread to simulate a client making a request and ignore the result let _ = thread::spawn(|| { simulate_client_request(); }); // Accept and handle only one connection, then shut down if let Some(stream) = listener.incoming().next() { match stream { Ok(mut stream) => { println!("๐ฆ Server: Connection accepted!"); handle_client(&mut stream)?; println!( "๐ Shutting down after sending the response." ); } Err(e) => { println!("โ Failed to accept connection: {}", e); } } } Ok(()) } /// Handles an incoming TCP stream by sending an HTTP response. /// /// This function demonstrates the use of the `Response` struct to send an HTTP response /// with status, headers, and a body. /// /// # Errors /// /// Returns a `ServerError` if there is an issue writing to the stream. fn handle_client(stream: &mut TcpStream) -> Result<(), ServerError> { println!("๐ฆ Server: Handling incoming connection..."); // Create an HTTP response with a 200 OK status let mut response = Response::new(200, "OK", b"