create a http server on a specific port and host in rust

To create an HTTP server on a specific port and host in Rust, you can use the hyper crate, which provides a high-level abstraction over HTTP and provides an easy-to-use API for creating servers.

Here's a simple example:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::service::service_fn;
use std::net::SocketAddr;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    let body = "Hello, World!".into();
    Ok(Response::new(body))
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); // the host and port to bind to

    let make_svc = service_fn(|req: Request<Body>| async move { handle_request(req) });

    let server = Server::bind(&addr).serve(make_svc);

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

This code creates an HTTP server that listens on 127.0.0.1:3000, and handles all incoming requests by calling the handle_request function. The handle_request function just returns a simple "Hello, World!" response.

Note that the tokio crate is used here to spawn a new asynchronous runtime to handle the server. In order to use the tokio runtime, you need to add it to your Cargo.toml dependencies:

[dependencies]
hyper = "0.14"
tokio = { version = "1", features = ["full"] }
77 chars
4 lines

This example should give you a basic understanding of how to create an HTTP server in Rust using hyper. From here, you can add more complex request handlers and middleware as needed.

gistlibby LogSnag