-1

我不能使用通过 #get 方法实现 FromRequest 的参数。它与#post完美配合

在下面的代码中,只要我不使用标头参数,/keyserver/key (GET) 就可以工作。否则,我得到一个:

GET /keyserver/key text/html:
    => Matched: GET /keyserver/key (key_list)
    => Outcome: Forward
    => Error: No matching routes for GET /keyserver/key text/html.
    => Warning: Responding with 404 Not Found catcher.
    => Response succeeded.

如何在 GET 方法中获取标头信息?

/keyserver/add_key (POST) 与标头参数配合良好。

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;

use rocket_contrib::json::Json;

extern crate serde;

use rocket::request::FromRequest;
use rocket::{Request, request};
use rocket::outcome::Outcome::{Success, Forward};

#[derive(Serialize, Deserialize, Debug)]
struct MyReply {
    uuid: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct RequestHeader {
    content_type: String,
}

impl<'a, 'r> FromRequest<'a, 'r> for RequestHeader {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> {
        let content_type = request.headers().get_one("Content-Type").unwrap_or("");
        if request.content_type().is_some() {
            Success(RequestHeader{
                content_type : content_type.to_string(),
            })
        } else {
            Forward(())
        }
    }
}

#[get("/key")]
fn key_list( /* header : RequestHeader*/ ) -> Json<MyReply> {
    //println!("my header {:?}", &header.content_type);
    let key = MyReply {
        uuid: "Bonjour".to_string(),
    };
    Json(key)
}

#[post("/add_key", format = "application/json", data = "<customer>")]
fn add_key(customer: Json<MyReply>, header : RequestHeader ) -> Json<MyReply> {
    println!("my header {:?}", &header.content_type);
    let key = MyReply {
        uuid: customer.uuid.clone(),
    };
    Json(key)
}

fn main() {
    rocket::ignite()
        .mount("/keyserver", routes![key_list, add_key])
        .launch();
}
4

1 回答 1

0

我找到了一个使用元组结构的解决方案

#[derive(Serialize, Deserialize, Debug)]
struct RequestHeader(String);

而不是以前的 RequestHeader 结构。

于 2020-05-15T14:26:24.003 回答