Skip to main content

ApiResponse

Struct ApiResponse 

Source
pub struct ApiResponse {
    pub code: i32,
    pub msg: String,
    pub data: Value,
}
Expand description

标准 API 响应结构体

严格对齐 PHP renderJson 输出格式:{code, msg, data},字段顺序固定。

§用法

use sz_rust_http_facade::response::ApiResponse;
use serde_json::json;

// 成功响应
let resp = ApiResponse::success(json!({"id": 1}), "ok");

// 错误响应
let resp = ApiResponse::error("参数错误");

// 自定义 code
let resp = ApiResponse::new(-1, "未登录", json!({}));

Fields§

§code: i32

业务状态码(1=成功,0=失败,-1=未登录,与 PHP BaseException 对齐)

§msg: String

业务消息

§data: Value

业务数据

Implementations§

Source§

impl ApiResponse

Source

pub fn new(code: i32, msg: impl Into<String>, data: Value) -> Self

创建新的 ApiResponse

Source

pub fn success(data: Value, msg: impl Into<String>) -> Self

创建成功响应(code=1)

对齐 PHP renderSuccess($data = [], $msg = '')

Source

pub fn success_empty() -> Self

创建成功响应(默认空 data + 空 msg)

Source

pub fn error(msg: impl Into<String>) -> Self

创建错误响应(code=0)

对齐 PHP renderError($msg = '', $data = [])

Source

pub fn error_with_data(msg: impl Into<String>, data: Value) -> Self

创建带数据的错误响应(code=0)

Source

pub fn error_with_code(code: i32, msg: impl Into<String>, data: Value) -> Self

创建带自定义错误码的错误响应

对齐 PHP renderError($code, $msg, $data)

Source

pub fn to_value(&self) -> Value

序列化为 serde_json::Value(保证字段顺序 code → msg → data)

使用 serde_json::Map(启用 preserve_order)保证插入顺序。

Source

pub fn to_json_string(&self) -> String

序列化为 JSON 字符串

Source

pub fn to_json_bytes(&self) -> Bytes

序列化为 bytes::Bytes(零拷贝引用计数字节容器)

P3 优化:替代 to_json_string 的 String 分配, 使用 serde_json::to_vec 序列化到 Vec<u8> 后转为 Bytes, 避免 String 的 UTF-8 验证开销,支持零拷贝传递。

输出与 to_json_string 逐字节一致。

Trait Implementations§

Source§

impl Clone for ApiResponse

Source§

fn clone(&self) -> ApiResponse

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ApiResponse

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoResponse for ApiResponse

让 ApiResponse 可以直接作为 axum handler 返回值

自动设置:

  • HTTP 状态码:200(无论业务 code 是 1 还是 0,HTTP 都是 200,对齐 PHP 行为)
  • Content-Type: application/json; charset=utf-8
Source§

fn into_response(self) -> Response

Create a response.
Source§

impl Serialize for ApiResponse

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T, S> Handler<IntoResponseHandler, S> for T
where T: IntoResponse + Clone + Send + Sync + 'static,

Source§

type Future = Ready<Response<Body>>

The type of future calling this handler returns.
Source§

fn call( self, _req: Request<Body>, _state: S, ) -> <T as Handler<IntoResponseHandler, S>>::Future

Call the handler with the given request.
Source§

fn layer<L>(self, layer: L) -> Layered<L, Self, T, S>
where L: Layer<HandlerService<Self, T, S>> + Clone, <L as Layer<HandlerService<Self, T, S>>>::Service: Service<Request<Body>>,

Apply a tower::Layer to the handler. Read more
Source§

fn with_state(self, state: S) -> HandlerService<Self, T, S>

Convert the handler into a Service by providing the state
Source§

impl<H, T> HandlerWithoutStateExt<T> for H
where H: Handler<T, ()>,

Source§

fn into_service(self) -> HandlerService<H, T, ()>

Convert the handler into a Service and no state.
Source§

fn into_make_service(self) -> IntoMakeService<HandlerService<H, T, ()>>

Convert the handler into a MakeService and no state. Read more
Source§

fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<H, T, ()>, C>

Convert the handler into a MakeService which stores information about the incoming connection and has no state. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more