9

这是从 Actix-Web 请求中获取内容类型标头的唯一可能性吗?这必须检查标头是否可用或者是否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();
4

2 回答 2

11

是的,这是“唯一”的可能性,但就是这样,因为:

  1. 标头可能不存在,headers().get(key)返回Option.
  2. 标头可能包含非 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.⏎

顺便说一句,您可能对警卫感兴趣:

web::route()
    .guard(guard::Get())
    .guard(guard::Header("content-type", "text/plain"))
    .to(handler)
于 2019-07-07T19:55:27.910 回答
0

我从路线中使用以下内容:

#[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

    // ...
}
于 2020-03-15T00:33:10.500 回答