toml
[dependencies]
actix-web = "4"
mysql = "25.0.0"
chrono = "0.4"
serde = { version = "1.0", features = ["derive"] }
rs
use actix_web::{get,post, web, App, HttpServer, Responder, HttpResponse, Error};
use mysql::*;
use mysql::prelude::*;
use serde::{Serialize,Deserialize};
#[derive(Debug, Serialize)]
struct User {
id: u64,
test: String,
num: u64,
}
#[derive(Deserialize,Serialize)]
struct Info {
test: String,
num: u64
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let url = "mysql://root:root@localhost:3306/fiber";
let pool = Pool::new(url).unwrap();
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone())) // 将连接池克隆并存储在应用状态中
//.route("/info",web::post().to(infos))
.service(infos)
.service(hello)
.service(index) // 使用 index 函数
})
.workers(8) // 设置工作线程数量
.bind(("127.0.0.1", 8080))?
.run()
.await
}
#[post("/info")]
async fn infos(infoo: web::Json<Info>) ->impl Responder {
let obj = Info {
test: infoo.test.to_string(),
num: infoo.num.clone()
};
web::Json(obj)
}
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[get("/getAll")]
async fn index(pool: web::Data<Pool>) -> Result<impl Responder, Error> {
let mut conn = pool.get_conn().map_err(|e| {
actix_web::error::ErrorInternalServerError(e)
})?;
// 执行查询并映射结果到 User 结构体
let results = conn.query_map(
"SELECT id, test, num FROM fiber_user",
|(id, test, num)| User { id, test, num },
).map_err(|e| {
actix_web::error::ErrorInternalServerError(e)
})?;
Ok(web::Json(results))
}
标签:web,actix,json,num,let,mysql,test
From: https://www.cnblogs.com/qcy-blog/p/18492214