如果我在 GET 上使用 FromRequest 参数,Rocket 找不到路线

Rocket cannot find a route if I use a FromRequest param on a GET

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

完美配合

在下面的代码中,只要我不使用 header 参数,/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 方法中获取 header 信息?

/keyserver/add_key (POST) 与 header 参数配合使用效果很好。

#![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();
}

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

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

而不是以前的 RequestHeader 结构。