[dependencies] hyper = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] } http-body-util = "0.1" hyper-util = { version = "0.1", features = ["full"] }
在Rust文件头部引入hyper与tokio的类型
1 2 3 4 5 6 7 8 9 10
use std::convert::Infallible; use std::net::SocketAddr;
use http_body_util::Full; use hyper::body::Bytes; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper::{Request, Response}; use hyper_util::rt::TokioIo; use tokio::net::TcpListener;
// We create a TcpListener and bind it to 127.0.0.1:3000 letlistener = TcpListener::bind(addr).await?;
// We start a loop to continuously accept incoming connections loop { let (stream, _) = listener.accept().await?;
// Use an adapter to access something implementing `tokio::io` traits as if they implement // `hyper::rt` IO traits. letio = TokioIo::new(stream);
// Spawn a tokio task to serve multiple connections concurrently tokio::task::spawn(asyncmove { // Finally, we bind the incoming connection to our `hello` service ifletErr(err) = http1::Builder::new() // `service_fn` converts our function in a `Service` .serve_connection(io, service_fn(hello)) .await { println!("Error serving connection: {:?}", err); } }); } }
// Resolve the root + user supplied path into the absolute path // this should hopefully remove any path traversals // if we fail to resolve path, we should return 404 root = match tokio::fs::canonicalize(&root).await { Ok(d) => d, Err(_) => returnOk(not_found()), };
// Ensure we are only looking for things in our public folder if !root.starts_with(original_root) { returnOk(not_found()); }
letmetadata = match tokio::fs::metadata(root.as_path()).await { Err(err) => returnOk(io_error(err)), Ok(metadata) => metadata, }; if metadata.is_dir() { // 如果root是路径,则添加index.html作为将读取的文件 root.push("index.html"); };
println!("Web server is available at http://{}\n", &address); if open { ifletErr(err) = open::that(format!("http://{}", &address)) { eprintln!("Failed to open URL in your browser: {}", err); } }
server.await.expect("Could not start web server"); }); }); ... } }