Да, это «единственная» возможность, но это так, потому что:
- Заголовок может не существовать,
headers().get(key)
возвращает Option
. - Заголовокможет иметь символы не 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)