Search code examples
rustrequestquery-stringrust-rocket

Rust Rocket, how to Access Data from a Request URI Query


I'm busy working with a Rust Rocket application and I was wondering if it is possible to access the data from a Request URI Query object from inside of a FromRequest implementation.

I have an example FromRequest implementation as

use rocket;
use rocket::{Config, Rocket, FromForm};
use rocket::request::{FromRequest, Request, Outcome};

#[tokio::main]
async fn main() {
    let figment = Config::figment().merge(("address", "0.0.0.0")).merge(("port", 31));
    let _rocket = Rocket::build()
        .configure(figment)
        .mount("/", rocket::routes![index])
        .launch().await.expect("ERROR");
}

#[rocket::get("/")]
fn index(_query_params:QueryParams) -> &'static str {
    return "Index";
}

#[derive(FromForm)]
pub struct QueryParams { _nothing:String }

#[rocket::async_trait]
impl<'r> FromRequest<'r> for QueryParams {
    type Error = rocket::Error;
    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        // get the query object
        let query = request.uri().query().unwrap();
        // check the contents of the query
        println!("{:?}", query);
        // below does not work because they are private fields
        let data_value = query.data.value;
        Outcome::Success(QueryParams { _nothing:String::from("nothing") })
    }
}

Using rocket = "0.5.0-rc.2"

If I do a test get request as

http://url.com:31/?param01%5Bkey01%5D=val01&param01%5Bkey02%5D=val02

I can get the following with the Debug Output

Query { source: None, data: Data { value: "param01%5Bkey01%5D=val01&param01%5Bkey02%5D=val02", decoded_segments: [uninitialized storage] } }

I can see the value is there and looks correct but I can't find any way of accessing it at this point because they are behind private fields.


Solution

  • For version 0.4: Use the Iterator implementation to get a sequence of FormItems, which have public fields raw, key, and value of type RawStr.

    For version 0.5-rc: Use the methods on Query listed here: https://api.rocket.rs/v0.5-rc/rocket/http/uri/struct.Query.html#impl, or, since it Derefs to RawStr, you can use any of RawStr's methods.