title: Rust Web Server example 01
tags: rust web server net
This code came via [ChatGPT](/ai/ChatGPT). [ChatGPT](/ai/ChatGPT) made a slight error with the `Cargo.toml`.
The actual Rust worked fine, and essentially is just regurgitated from the official docs.
We got
```rust
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;
async fn handle_request(_: Request
) -> Result, Infallible> {
// Create a response with a simple message
let response = Response::builder()
.status(200)
.header("Content-Type", "text/plain")
.body(Body::from("Hello, Rust Web Server!"))
.unwrap();
Ok(response)
}
#[tokio::main]
async fn main() {
// Create a new server bound to 127.0.0.1:3000
let addr = ([127, 0, 0, 1], 3000).into();
let make_svc = make_service_fn(|_conn| {
async { Ok::<_, Infallible>(service_fn(handle_request)) }
});
let server = Server::bind(&addr).serve(make_svc);
println!("Server running at http://127.0.0.1:3000/");
if let Err(e) = server.await {
eprintln!("Server error: {}", e);
}
}
```
and the `Cargo.toml` we got was
```toml
[package]
name = "web1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
hyper = "0.14"
tokio = { version = "1", features = ["full"] }
```
which needeed the `hyper =` line to be fixed to
```toml
hyper = { version = "0.14", features = ["http2","server","tcp"] }
```
and then this compiled and ran.