How to get Cookie from Request in Actix 2.0

Viewed 2495

I want to get cookie's value from request. I found that in Actix 0.x.x, cookie's value could be get from calling

fn get_cookie(req: HttpRequest) {
    let cookie = req.cookie("name") <-- Here

    return HttpResponse::Ok()
        .body(
            format!("{}", cookie);
        )
}

I'm quite new to Rust and Actix. Currently I'm parsing it from declared function which get string of HttpRequest.headers(). I'm not sure if there's a straight forward to get cookie like in Actix 0.x.x.

pub fn get_cookie(req: HttpRequest, name: &str) -> String {
    let cookie: Vec<&str> = req
        .headers()
        .get("cookie")
        .unwrap()
        .to_str()
        .unwrap()
        .split("&")
        .collect();

    let auth_token: Vec<&str> = cookie
        .into_iter()
        .filter(|each| {
            let body: Vec<&str> = each.split("=").collect();

            body[0] == name
        })
        .collect();

    let cookie_part: Vec<&str> = auth_token[0].split("=").collect();

    cookie_part[1].to_owned() 
}
1 Answers
Related