I am fairly new to rust so trying to find the proper way to handle this specific use case. We are using actix web server and have created a route which maps to the following function:
#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct Status {
status: u32,
description: String,
}
#[derive(serde::Deserialize, serde::Serialize, Debug)]
pub struct Headers {
header1: String,
header2: String,
header3: String,
header4: String,
}
pub trait Parse<T>: Sized {
fn parse(value: T) -> Option<Self>;
}
impl Parse<&HeaderMap> for Headers {
fn parse(headers: &HeaderMap) -> Option<Self> {
let header1 = headers.get("header1")?.to_str().ok()?;
let header2 = headers.get("header2")?.to_str().ok()?;
let header3 = headers.get("header3")?.to_str().ok()?;
let header4 = headers.get("header4")?.to_str().ok()?;
Some(Headers {
header1: String::from(header1),
header2: String::from(header2),
header3: String::from(header3),
header4: String::from(header4),
})
}
}
pub async fn config(_req: HttpRequest, req: HttpRequest) -> impl Responder {
println!("{:?}", req);
let possible_headers = Headers::parse(req.headers());
let mut response = HttpResponse::Ok();
let mut return_result = Status {
status: 200,
description: String::from("Successful"),
};
match possible_headers {
Some(headers) => {
println!("{:?}", headers);
}
None => {
println!("BAD REQUEST");
return_result.status = 400;
return_result.description = String::from("Bad request");
response = HttpResponse::BadRequest()
}
}
response.json(return_result)
}
Is there any easier way to convert the header map into a guaranteed type? I have done this by attempting to retrieve the header from the header map then adding it to the Headers struct.
I'm also thinking we could use generics to retrieve the types from the headermap to the Headers struct.