6

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() 
}
SaltyAom
  • 81
  • 2
  • 4
  • For authentication, you can probably just use middleware. There is a provided `IdentityService` which you can configure with a `CookieIdentityPolicy`, and then obtain the identity in handlers using the `Identity` extractor. – Peter Hall Jul 01 '20 at 07:39

1 Answers1

5

HttpRequest implements HttpMessage which has a cookie method so just call that?

Masklinn
  • 34,759
  • 3
  • 38
  • 57