【Rust笔记】Rocket实现自定义的Responder

在Java项目中,我们通常会将响应包装一层来实现统一响应格式,在Rocket中,我们也可以通过实现Responder来返回统一的响应。

res.rs

rust 复制代码
use crate::api::err::Error;
use rocket::response::Responder;
use rocket::serde::json::json;
use rocket::serde::{Deserialize, Serialize};
use rocket::Request;

#[derive(Serialize, Deserialize)]
pub struct Res<'a, T> {
    code: i32,
    msg: &'a str,
    data: Option<T>,
}

impl<T> Res<T> {
    pub fn success(data: T) -> Self {
        Res {
            code: 0,
            msg: "",
            data: Some(data),
        }
    }

    pub fn error(msg: &str) -> Self {
        Res {
            code: 1,
            msg,
            data: None,
        }
    }

    pub fn from_error(error: Error) -> Self {
        Res {
            code: error.0,
            msg: error.1,
            data: None,
        }
    }
}

impl<'r, 'o: 'r, T: Serialize> Responder<'r, 'o> for Res<T> {
    fn respond_to(self, request: &'r Request<'_>) -> rocket::response::Result<'o> {
        json!(&self).respond_to(request)
    }
}

err.rs

rust 复制代码
pub type Error<'a> = (i32, &'a str);

pub const ANY: Error = (1, "system error");
pub const SOURCE_NOT_EMPTY: Error = (1001, "source is not empty");

然后就可以按具体处理结果返回统一的失败或者成功响应:

  • 成功:

    rust 复制代码
    Res::success(source)
  • 失败:

    rust 复制代码
    Res::error("失败原因")
  • 自定义失败code:

    rust 复制代码
    Res::from_error((10001,"失败原因"))

    或者在err.rs中添加错误类型后:

    rust 复制代码
    Res::from_error(err::SOURCE_NOT_EMPTY)
相关推荐
mqiqe34 分钟前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim37 分钟前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
脉动数据行情40 分钟前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
爱学习的小邓同学1 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
红尘散仙2 小时前
TypeScript WIT Guest:类型约束与 ComponentizeJS 工程化
rust·typescript·webassembly
zx_741484812 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python
Oll Correct2 小时前
Adobe illustrator 案例九:百宝箱图标绘制
笔记·ui·adobe·illustrator
小灰灰搞电子2 小时前
Rust+Slint 实现的“DNA双螺旋”加载动画源码分享
后端·rust·slint·加载动画
红尘散仙2 小时前
从 dsh 的插件系统出发:为什么我要探索 WIT 与 Wasm Component Model
rust·typescript·webassembly
红尘散仙2 小时前
从 WIT 到 Wasmtime:构建 Rust Component 工程
rust·typescript·webassembly