pubasyncfntodo(info: web::Path<Info>, db_pool: web::Data<Pool>) -> impl Responder { let client: Client = db_pool .get() .await .expect("Error connecting to the database");
let result = get_todo(&client, info.list_id).await; match result { Ok(todo) => HttpResponse::Ok().json(todo), Err(_) => HttpResponse::InternalServerError().into(), } }
use actix_web::{get, middleware, web, App, HttpServer, Responder};
use env_logger; use log::info;
// ...
asyncfnmain() -> io::Result<()> { dotenv().ok(); + if std::env::var("RUST_LOG").is_err() { + std::env::set_var("RUST_LOG", "actix_web=info"); + } + env_logger::init(); let cfg = crate::config::Config::from_env().unwrap(); let pool = cfg.pg.create_pool(NoTls).unwrap(); + info!( "Starting server at http://{}:{}", cfg.server.host, cfg.server.port ); HttpServer::new(move || { App::new() .data(pool.clone()) + .wrap(middleware::Logger::default()) // ...
运行以查看日志
$ cargo run Compiling todo-list v0.1.0 (/Users/qiwihui/rust/todo-list) Finished dev [unoptimized + debuginfo] target(s) in 1m 19s Running `target/debug/todo-list` [2020-10-23T06:43:18Z INFO todo_list] Starting server at http://127.0.0.1:8000 [2020-10-23T06:43:18Z INFO actix_server::builder] Starting 4 workers [2020-10-23T06:43:18Z INFO actix_server::builder] Starting "actix-web-service-127.0.0.1:8000" service on 127.0.0.1:8000 [2020-10-23T06:45:04Z INFO actix_web::middleware::logger] 127.0.0.1:63751 "GET /todos HTTP/1.1" 200 79 "" "curl/7.64.1" 0.016465
如何获取请求体
首先,我们增加插入数据操作,sql 语句中的 returning id, title 用于返回插入成功的数据
pubasyncfncreate_todo( info: web::Json<CreateTodoList>, state: web::Data<AppState>, ) -> impl Responder { let client: Client = state .pool .get() .await .expect("Error connecting to the database"); let result = db::create_todo(&client, info.0.title.clone()).await; match result { Ok(todo) => HttpResponse::Ok().json(todo), Err(_) => HttpResponse::InternalServerError().into(), } }
其中,state: web::Data<AppState> 将 原来的 pool 做了简单的封装,好处在于可以传入多个数据作为 web::Data。