Actix-Web框架是目前性能上数一数二的rust的web框架,它的性能远超spring,nestJS, gin等目前流行的框架。
仅仅是返回hello,wold,我发现actix-web的性能就已经是gin的3倍。但是使用actix-web的缺点也非常明显,就是代码通过编译非常困难(也许是我太菜了)。
我实践了actix-web的以下功能:
- 静态文件
- 错误处理
- post一个json参数
本服务器用于提交易班账号信息
首先在文件结构上
page页面用于存放静态页面,src内容是代码文件,configure_parse用于解析配置文件,配置文件格式是toml,db_handler用于处理数据库,response用于统一处理错误。APITEST用于测试接口。main.rs是主函数。开发过程中使用命令cargo watch -x run
,可以热编译。需要安装:cargo install cargo-watch
大概需要下面这些依赖
[dependencies]
actix-web = "4"
actix-files = "0.6.0"
derive_more = "0.99.17"
sqlx = { version = "0.5.11", features = ["runtime-actix-native-tls", "mysql"] }
exitcode = "1.1.2"
serde = { version = "1.0.136" ,features=["derive"]}
serde_json = "1.0.79"
futures-util = { version = "0.3.7", default-features = false, features = ["std"] }
validator = { version = "0.12", features = ["derive"] }
toml = "0.5.8"
HTTP服务器
官方的API文档给出了一个简单的例子
use actix_web::{
get, web, App, HttpServer, Responder};
#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
format!("Hello {name}!")
}
#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/hello", web::get().to(|| async {
"Hello World!" }))
.service(greet)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
在宏的加持下,使用rust构建HTTP服务器也是比较简单的,只需要简简单单的几行代码就可以搞定。
静态文件
显示静态文件也不是非常困难,我们在网页路径和本地的路径之间建立映射关系。
为了在网站的根目录也能显示网页,我们还需要单独处理一下get(“/”)这种情况,我们稍稍修改一下hello函数
use actix_files::{
NamedFile};
#[get("/")]
async fn hello() -> Result<NamedFile> {
Ok(NamedFile::open(PathBuf::from("./page/index.html"))?)
}
这样就可以显示静态页面了
统一处理错误
// response/result.rs
use actix_web::{
error, HttpResponse, HttpResponseBuilder};
use actix_web::body::BoxBody;
use actix_web::http::{
header, StatusCode};
use derive_more::{
Display, Error};
use serde_json::json;
#[derive(Display, Debug)]
pub enum YiBanResponseError {
#[display(fmt = "格式化错误 :{}", _0)]
FormatError(&'static str),
#[display(fmt = "服务器错误 : {}", _0)]
ServerError(&'static str),
#[display(fmt = "数据库错误 : {}", _0)]
DBError(&'static str),
#[display(fmt =