这是从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();

推荐答案

是的,这是"唯一"的可能性,但这是因为:

  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.⏎

顺便说一下,你可能对guards感兴趣:

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

Rust相关问答推荐

Rust为什么应用于引用的操作符可以强制,而具有显式类型的let则不能?

为什么在Rust struct 中只允许最后一个字段具有动态大小的类型

在‘await’点上使用‘std::同步::Mutex’是否总是会导致僵局?

在Tauri中获取ICoreWebView 2_7以打印PDF

什么样的 struct 可以避免使用RefCell?

MPSC频道在接收器处阻塞

有没有办法避免在While循环中多次borrow `*分支`

为什么铁 rust S的默认排序功能比我对小数组的 Select 排序稍微慢一些?

作为1字节位掩码的布尔值 struct

如何在函数中返回自定义字符串引用?

如何实现Serde::Ser::Error的调试

为什么 vec![Vec::with_capacity(n)] 为子向量创建 0 容量?

为什么将易错函数的泛型结果作为泛型参数传递 infer ()?不应该是暧昧的吗?

结果流到 Vec 的结果:如何避免多个into_iter和collect?

Google chrome 和 Apple M1 中的计算着色器

Rust 程序中的内存泄漏

为什么不可变特征的实现可以是可变的?

没有通用参数的通用返回

Rust 内联 asm 中的向量寄存器:不能将 `Simd` 类型的值用于内联汇编

Rust 为什么 (u32, u32) 的枚举变体的大小小于 (u64)?