这是从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();
这是从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();
是的,这是"唯一"的可能性,但这是因为:
headers().get(key)
返回Option
.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)