Rust actix_web框架简单示例

@[Rust actix_web框架简单示例]

接口设计

学习了解下Rust语言以及Rust Web开发,
示例只设计两个接口,分别为添加用户和查找用户

POST /user 添加用户

Body 参数(application/json)

{
	"name": "测试用户",
	"age": 18
}

GET /user/{name} 获取用户**

返回示例

{
	"code": 0,
	"msg": "获取用户成功",
	"user": {
		"name": "测试用户",
		"age": 18
	}
}

测试接口

curl -X POST -H 'Content-Type:application/json' -d '{"name": "leo1", "age": 18}' http://localhost:8001/user
curl -X POST -H 'Content-Type:application/json' -d '{"name": "leo2", "age": 18}' http://localhost:8001/user
curl -X POST -H 'Content-Type:application/json' -d '{"name": "leo3", "age": 18}' http://localhost:8001/user
curl http://localhost:8001/user/leo1
curl http://localhost:8001/user/leoxxx
curl http://localhost:8001/user/leo2

在这里插入图片描述

源码

main.rs

use actix_web::{get, middleware::Logger, post, web, App, HttpServer, Responder, Result};
use env_logger::Env;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Mutex};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    age: i32,
}

#[derive(Debug, Serialize)]
struct JsonResult {
    code: i32,
    msg: String,
    user: User,
}

#[derive(Debug)]
struct UserStore {
    //  多个线程修改需要使用Mutex, 参考:
    //  https://actix.rs/docs/application/
    users: Mutex<HashMap<String, i32>>,
}

#[get("/user/{name}")]
async fn get_user(name: web::Path<String>, state: web::Data<UserStore>) -> Result<impl Responder> {
    let name = name.into_inner();
    let users = state.users.lock().unwrap();
    let r = match users.get(&name) {
        Some(v) => JsonResult {
            code: 0,
            msg: format!("success found user {}", name),
            user: User {
                name: name,
                age: *v,
            },
        },
        None => JsonResult {
            code: -1,
            msg: format!("user {} not found", name),
            user: User {
                name: "".to_string(),
                age: -1,
            },
        },
    };

    Ok(web::Json(r))
}

#[post("/user")]
async fn add_user(u: web::Json<User>, state: web::Data<UserStore>) -> Result<impl Responder> {
    let mut users = state.users.lock().unwrap();
    users.insert(u.name.to_string(), u.age);
    let r = JsonResult {
        code: 0,
        msg: format!("add user {} age {} success", u.name, u.age),
        user: User {
            name: u.name.to_string(),
            age: u.age,
        },
    };
    println!("users is : {:?}", users);
    Ok(web::Json(r))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(Env::default().default_filter_or("info"));

    let users = web::Data::new(UserStore {
        users: Mutex::new(HashMap::new()),
    });

    HttpServer::new(move || {
        App::new()
            // 共享一个哈希表给所有路由,存储用户信息
            .app_data(users.clone())
            .wrap(Logger::default())
            .wrap(Logger::new("%a %s"))
            .service(get_user)
            .service(add_user)
    })
    .bind(("localhost", 8001))?
    .run()
    .await
}

ini

[package]
name = "actix-demo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "4"
env_logger = "0.9.0"
actix-session = { version = "0.6", features = ["cookie-session"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
json = "0.12"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Rust的actix-web框架中,`Responder`和`ResponseError`是用于处理HTTP响应的重要trait。它们允许你定义如何将数据转换为HTTP响应以及如何处理错误。 `Responder` trait用于将数据转换为HTTP响应。你可以在自定义的类型上实现`Responder` trait,以便该类型可以直接返回给actix-web的处理器函数。以下是一个示例: ```rust use actix_web::{HttpResponse, Responder}; struct MyData { // 数据结构 } impl Responder for MyData { type Error = actix_web::Error; type Future = Result<HttpResponse, Self::Error>; fn respond_to(self, _: &actix_web::HttpRequest) -> Self::Future { // 将数据转换为HttpResponse let response = HttpResponse::Ok().json(self); // 假设MyData实现了serde的Serialize trait Ok(response) } } ``` 在这个示例中,我们为自定义的`MyData`类型实现了`Responder` trait。我们通过实现`respond_to`方法来定义如何将数据转换为HTTP响应。在这个例子中,我们使用`HttpResponse::Ok().json(self)`将`MyData`转换为JSON格式的HTTP响应。 `ResponseError` trait用于处理错误并生成适当的HTTP响应。你可以在自定义的错误类型上实现`ResponseError` trait,以便actix-web可以捕获并处理这些错误。以下是一个示例: ```rust use actix_web::{HttpResponse, ResponseError}; use std::convert::From; #[derive(Debug)] struct MyError { // 错误信息 } impl ResponseError for MyError { fn error_response(&self) -> HttpResponse { // 生成适当的HTTP响应 HttpResponse::InternalServerError().body("Internal Server Error") } } impl From<actix_web::Error> for MyError { fn from(_: actix_web::Error) -> Self { MyError { // 从actix-web的Error转换为自定义的错误类型 } } } ``` 在这个示例中,我们为自定义的`MyError`类型实现了`ResponseError` trait。我们通过实现`error_response`方法来定义如何生成适当的HTTP响应。在这个例子中,我们直接返回一个带有"Internal Server Error"消息的500错误响应。 另外,我们还实现了`From<actix_web::Error>` trait,以便将actix-web的错误转换为我们自定义的错误类型。这样,在处理请求时,actix-web可以自动将错误转换为我们定义的`MyError`类型。 希望这可以帮助你理解和使用`Responder`和`ResponseError` trait!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值