带参数的 Rust Get 请求

时间:2021-04-09 17:17:53

标签: rust actix-web

我在实现 #[async_trait]

中有以下异步函数
pub async fn get_field_value(field: web::Path<String>, value: web::Path<String>) -> HttpResponse {
    let json_message = json!({
        "field": field.0,
        "value": value.0
    });
    HttpResponse::Ok().json(json_message)
}

现在我有我的路由器功能

pub fn init_router(config: &mut ServiceConfig){
    config.service(web::resource("/get/field-value/{field}/{value}").route(web::get().to(get_field_value)));
}

然后在运行网络应用程序时:localhost:3000/get/field-value/name/James
如果不是我收到以下错误,我就不会得到 Json:

wrong number of parameters: 2 expected 1

我认为我不应该收到错误,因为我正确地初始化了参数中的值。 #[async_trait] 都不允许我使用 #[get("/get/field-value/{field}/{value}")]

1 个答案:

答案 0 :(得分:1)

我认为路由处理程序被赋予一个包含路由模式中所有值的参数,而不是两个单独的字符串参数。您可以使用元组来获取这两个值:

pub async fn get_field_value(field: web::Path<(String, String)>) -> HttpResponse

或者您可以使用 serde 为您反序列化路由模式中的字段:

#[derive(Serialize, Deserialize)]
pub struct Field {
    pub field: String,
    pub value: String,
}

pub async fn get_field_value(data: web::Path<Field>) -> HttpResponse {
    let json_message = json!({
        "field": data.field,
        "value": data.value
    });
    HttpResponse::Ok().json(json_message)
}