-1

I cannot use a param that implements FromRequest with a method #get. It works perfectly with a #post

In the code below, the /keyserver/key (GET) works as long as I don't use the header param. Otherwise, I get a :

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.

How can I get the header information in a GET method?

The /keyserver/add_key (POST) works well with the header param.

#![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();
}
the duck
  • 375
  • 3
  • 13

1 Answers1

0

I found a solution using a tuple struct

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

instead of the former RequestHeader struct.

the duck
  • 375
  • 3
  • 13