You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Axum路由处理并返回不同Content-Type的响应?

实现根据查询参数返回不同响应的Rust Axum接口

需求说明

当用户访问http://127.0.0.1:8080/hello时,根据查询参数id的不同返回对应响应:

id(输入)状态码Content-Type响应体
1200application/json{"name": "world"}
2400text/plainno such person

完整实现代码

首先确保Cargo.toml包含必要依赖:

[dependencies]
axum = "0.7"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }

然后实现hello_get函数及完整逻辑:

use axum::{
    extract::Query,
    http::StatusCode,
    response::{IntoResponse, Json, Response},
    Router, routing::get,
};
use serde::Deserialize;

// 用于解析查询参数的结构体,需派生Deserialize trait
#[derive(Deserialize)]
struct HelloParam {
    id: u16,
}

// 用于生成JSON响应的结构体,需派生Serialize trait
#[derive(serde::Serialize)]
struct HelloResponse {
    name: String,
}

async fn hello_get(Query(params): Query<HelloParam>) -> Response {
    match params.id {
        // id=1时返回JSON响应,自动设置Content-Type与200状态码
        1 => Json(HelloResponse {
            name: "world".to_string(),
        }).into_response(),
        // id=2时返回400状态码的纯文本响应
        2 => (StatusCode::BAD_REQUEST, "no such person").into_response(),
        // 处理其他未定义id的情况,可按需调整
        _ => (StatusCode::NOT_FOUND, "unknown id").into_response(),
    }
}

#[tokio::main]
async fn main() {
    let router = Router::new().route("/hello", get(hello_get));

    axum::Server::bind(&"127.0.0.1:8080".parse().unwrap())
        .serve(router.into_make_service())
        .await
        .unwrap();
}

关键说明

  1. 序列化/反序列化支持:HelloParam通过Deserialize trait实现从URL查询参数中解析数据;HelloResponse通过Serialize trait实现序列化为JSON格式。
  2. 响应自动转换:Axum的IntoResponse trait会自动处理响应头与状态码:
    • Json类型会自动设置Content-Type: application/json和200状态码。
    • (StatusCode, &str)元组会生成对应状态码的纯文本响应,自动设置Content-Type: text/plain。
  3. 分支逻辑扩展:通过match语句匹配不同id值,可灵活添加更多参数分支的处理逻辑。

内容的提问来源于stack exchange,提问作者progquester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:55:19