有没有更简单的方法来获取 Actix-Web HTTP header 的字符串值?

Is there simpler method to get the string value of an Actix-Web HTTP header?

这是从 Actix-Web 请求中获取 content-type header 的唯一可能性吗?这必须检查 header 是否可用或者 to_str 是否失败...

let req: actix_web::HttpRequest;

let content_type: &str = req
    .request()
    .headers()
    .get(actix_web::http::header::CONTENT_TYPE)
    .unwrap()
    .to_str()
    .unwrap();

是的,这是 "only" 的可能性,但它是这样的,因为:

  1. header可能不存在,headers().get(key)returnsOption.
  2. header 可能有 non-ASCII 个字符,HeaderValue::to_str 可能会失败。

actix-web 让您可以单独处理这些错误。

为简化起见,您可以创建一个不区分这两个错误的辅助函数:

fn get_content_type<'a>(req: &'a HttpRequest) -> Option<&'a str> {
    req.headers().get("content-type")?.to_str().ok()
}

完整示例:

use actix_web::{web, App, HttpRequest, HttpServer, Responder};

fn main() {
    HttpServer::new(|| App::new().route("/", web::to(handler)))
        .bind("127.0.0.1:8000")
        .expect("Cannot bind to port 8000")
        .run()
        .expect("Unable to run server");
}

fn handler(req: HttpRequest) -> impl Responder {
    if let Some(content_type) = get_content_type(&req) {
        format!("Got content-type = '{}'", content_type)
    } else {
        "No content-type header.".to_owned()
    }
}

fn get_content_type<'a>(req: &'a HttpRequest) -> Option<&'a str> {
    req.headers().get("content-type")?.to_str().ok()
}

这会给你结果:

$ curl localhost:8000
No content-type header.⏎
$ curl localhost:8000 -H 'content-type: application/json'
Got content-type = 'application/json'⏎
$ curl localhost:8000 -H 'content-type: '
No content-type header.⏎

顺便说一下,您可能对 guards:

感兴趣
web::route()
    .guard(guard::Get())
    .guard(guard::Header("content-type", "text/plain"))
    .to(handler)

我使用以下路线:

#[get("/auth/login")]
async fn login(request: HttpRequest, session: Session) -> Result<HttpResponse, ApiError> {
    let req_headers = request.headers();

    let basic_auth_header = req_headers.get("Authorization");
    let basic_auth: &str = basic_auth_header.unwrap().to_str().unwrap();
    // Keep in mind that calling "unwrap" here could make your application
    // panic. The right approach at this point is to evaluate the resulting
    // enum variant from `get`'s call

    println!("{}", basic_auth); // At this point I have the value of the header as a string

    // ...
}