rust zero_to_production

learning rust


Heavy Lifting we need to take care of

  1. choose a web framework to get familiar
  2. define our testing strategy
  3. choose a crate to interact with our database
  4. defube how we want ot manage changes to our databse schemas over time a.k.a migrations
  5. actually write some queries

A Basic Health Check

new project

cargo new $(PROJECTNAME)

Wiring Up actix-web

use actix_web::{web,App,HttpRequest,HttpServer,Responder};
 
async fn greet(req :HttpRequest) -> impl Responder{
    let name = req.match_info().get("name").unwrap_or("World");
    format!("Hello {}",name)
}
 
#[tokio::main]
async fn main() -> std::io::Result<()>{
    HttpServer::new(|| {
        App::new()
            .route("/",web::get().to(greet))
            .route("/{name}",web::get().to(greet))
    })
        .bind("localhost:8023")?
        .run()
        .await
}
  • use cargo ckeck will thrown a problem

install actix-web

[package]
name = "rust-zero-to-production"
version = "0.1.0"
edition = "2021"
 
[dependencies]
actix-web = "4.0.0"
tokio = {version = "1",features = ["macros","rt-multi-thread"]}
  • 除了將library直接裝載toml上也可以使用指令
    • 但要先安裝cargo install cargo-edit
  • 使用cargo add安裝
    • cargo add actix-web --vers 4.0.0

Anatomy Of An actix-web Application

For the greet function

async fn greet(req :HttpRequest) -> impl Responder{
  [...]
}
  • greet is an asynchronous function that takes an HttpRequest as input and returns something they implments the Responder trait

For the tokio

#[tokio::main]
async fn main() -> std::io::Result<()>{
  [...]
}
  • What is tokio doing here