web server in rust

To create a web server in Rust, we can use the actix-web framework which is a powerful, pragmatic, and extremely fast web framework written in Rust.

Here are the steps to create a basic web server using actix-web:

  1. Create a new Rust project using cargo:

    main.rs
    cargo new my_app
    
    17 chars
    2 lines
  2. Add the actix-web dependency in Cargo.toml:

    [dependencies]
    actix-web = "3.3.2"
    
    35 chars
    3 lines
  3. Create a new file main.rs in the src directory and add the following code to it:

    main.rs
    use actix_web::{get, App, HttpResponse, HttpServer, Responder};
    
    #[get("/")]
    async fn index() -> impl Responder {
        HttpResponse::Ok().body("Hello, World!")
    }
    
    #[actix_rt::main]
    async fn main() -> std::io::Result<()> {
        HttpServer::new(|| App::new().service(index))
            .bind("127.0.0.1:8080")?
            .run()
            .await
    }
    
    336 chars
    15 lines

    This code sets up a basic web server that responds to GET requests to the root path / with the message "Hello, World!".

  4. Run the web server using cargo:

    main.rs
    cargo run
    
    10 chars
    2 lines
  5. Open a web browser and navigate to http://127.0.0.1:8080/. You should see the "Hello, World!" message displayed in the browser.

That's it! You have created a basic web server in Rust using the actix-web framework. From here, you can customize and add more routes to your web server as needed.

gistlibby LogSnag