create a http server with a specific route and a specific status code in rust

To create an HTTP server with a specific route and a specific status code in Rust, you can use the hyper crate, which provides a low-level API for building HTTP servers.

Here is an example code that creates an HTTP server with a single route /hello that responds with a 200 status code and a message of "Hello, World!":

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;

async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    let body = "Hello, World!".into();
    Ok(Response::new(body))
}

#[tokio::main]
async fn main() {
    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, Infallible>(service_fn(hello))
    });

    let addr = ([127, 0, 0, 1], 3000).into();
    let server = Server::bind(&addr).serve(make_svc);

    println!("Listening on http://{}", addr);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
644 chars
25 lines

In this code, the hello function is the handler for the /hello route. It takes a Request object as an argument and returns a Response object. The Response object is created using the hyper::Response::new constructor, which takes the body of the response as an argument.

The make_service_fn function creates a closure that returns a service for each connection. The service_fn function creates a service that handles each request by calling the hello function.

The Server::bind function creates a new Server instance that listens on the specified address and serves the provided service.

When you run this code, the server will listen on http://127.0.0.1:3000. If you make a GET request to http://127.0.0.1:3000/hello, you should receive a response with a 200 status code and the message "Hello, World!".

gistlibby LogSnag